Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

หาค่าผกผันของอาร์เรย์ 3 มิติใน Python ด้วย numpy.linalg.tensorinv()

เพื่อคำนวณค่าผกผัน (inverse) ของอาร์เรย์ 3 มิติ ให้ใช้ numpy.linalg.tensorinv() ผลลัพธ์คือ inverse สำหรับการดำเนินการ tensordot คือ tensordot(tensorinv(a), a, ind) จะได้ identity tensor พารามิเตอร์ ind คือจำนวนดัชนีแรกที่เกี่ยวข้องกับการ inverse ค่าเริ่มต้นคือ 2

ขั้นตอนการใช้งาน

import numpy as np
from numpy.linalg import inv

สร้างอาร์เรย์และปรับรูปร่าง

arr = np.eye(4*6)
arr.shape = (24, 8, 3)
print("Our Array...\n", arr)
print("\nDimensions of our Array...\n", arr.ndim)
print("\nDatatype of our Array object...\n", arr.dtype)
print("\nShape of our Array object...\n", arr.shape)

คำนวณ inverse ด้วย ind=1

print("\nResult...\n", np.linalg.tensorinv(arr, ind=1))

โค้ดตัวอย่างสมบูรณ์

import numpy as np
from numpy.linalg import inv

arr = np.eye(4*6)
arr.shape = (24, 8, 3)
print("Our Array...\n", arr)
print("\nDimensions of our Array...\n", arr.ndim)
print("\nDatatype of our Array object...\n", arr.dtype)
print("\nShape of our Array object...\n", arr.shape)
print("\nResult...\n", np.linalg.tensorinv(arr, ind=1))

ผลลัพธ์ที่คาดหวัง

Our Array...
[[[1. 0. 0.] ... [0. 0. 0.]] ... ]
Dimensions of our Array...
3
Datatype of our Array object...
float64
Shape of our Array object...
(24, 8, 3)
Result...
[[[1. 0. 0. ... 0. 0. 0.] ... ] ... ]