เพื่อแก้สมการเทนเซอร์ (tensor equation) ให้ใช้ numpy.linalg.tensorsolve() สมมติว่าดัชนีทั้งหมดของ x ถูกรวมในผลคูณ พร้อมกับดัชนีขวาสุดของ a คล้ายกับ tensordot(a, x, axes=b.ndim)
พารามิเตอร์สำคัญ
- a: เทนเซอร์係พ รูปร่าง b.shape + Q โดย Q ต้องทำให้ prod(Q) == prod(b.shape)
- b: เทนเซอร์ด้านขวา รูปร่างใดก็ได้
- axes (ไม่บังคับ): แกนใน a ที่จะจัดเรียงใหม่ไปขวาก่อน inversion
ขั้นตอนการใช้งาน
import numpy as np
สร้างเทนเซอร์ a และ b
arr1 = np.eye(2*3*4)
arr1.shape = (2*3, 4, 2, 3, 4)
arr2 = np.random.randn(2*3, 4)
print("Array1...\n", arr1)
print("\nArray2...\n", arr2)
print("\nDimensions of Array1...\n", arr1.ndim)
print("\nDimensions of Array2...\n", arr2.ndim)
print("\nShape of Array1...\n", arr1.shape)
print("\nShape of Array2...\n", arr2.shape)
แก้สมการเทนเซอร์
print("\nResult...\n", np.linalg.tensorsolve(arr1, arr2))
โค้ดตัวอย่างสมบูรณ์
import numpy as np
arr1 = np.eye(2*3*4)
arr1.shape = (2*3, 4, 2, 3, 4)
arr2 = np.random.randn(2*3, 4)
print("Array1...\n", arr1)
print("\nArray2...\n", arr2)
print("\nDimensions of Array1...\n", arr1.ndim)
print("\nDimensions of Array2...\n", arr2.ndim)
print("\nShape of Array1...\n", arr1.shape)
print("\nShape of Array2...\n", arr2.shape)
print("\nResult...\n", np.linalg.tensorsolve(arr1, arr2))
ผลลัพธ์ที่คาดหวัง (ตัวอย่าง)
Array1... (identity tensor reshaped) Array2... (random values) Dimensions of Array1... 5 Dimensions of Array2... 2 Shape of Array1... (6, 4, 2, 3, 4) Shape of Array2... (6, 4) Result... [[[ 0.31376716 0.63443741 0.58628101 0.62313096] [ 1.12528958 -1.18403238 -0.64663325 -0.24241201] [ 0.55598965 -2.00059925 -1.97946414 -1.72478953]] [[ 0.18976226 0.60572953 1.50157692 -2.4491463 ] [ 0.42461806 -2.17872016 0.49677904 -1.11634625] [-1.09074462 0.35475618 0.42474987 -1.34391368]]]