在 Python 中求解張量方程
要解決張量方程,請在 Python 中使用 numpy.linalg.tensorsolve() 方法。假設 x 的所有索引都在乘積中累加,以及 a 最右邊的索引,就像在例如 tensordot(a, x, axes=b.ndim) 中一樣。
第一個引數 a 是一個係數張量,形狀為 b.shape + Q。Q 是一個元組,等於由 a 的適當數量的最右邊索引組成的子張量的形狀,並且必須滿足 prod(Q) == prod(b.shape)。第二個引數 b 是一個右手張量,可以是任何形狀。第三個引數 axis 是 a 中要重新排序到右側的軸,在求逆之前。如果為 None(預設值),則不執行重新排序。
步驟
首先,匯入所需的庫 -
import numpy as np
使用 array() 方法建立兩個 NumPy 陣列
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)要解決張量方程,請在 Python 中使用 numpy.linalg.tensorsolve() 方法。假設 x 的所有索引都在乘積中累加,以及 a 最右邊的索引,就像在例如 tensordot(a, x, axes=b.ndim) 中一樣 -
print("\nResult...\n",np.linalg.tensorsolve(arr1, arr2))示例
import numpy as np
# Creating two numpy arrays using the array() method
arr1 = np.eye(2*3*4)
arr1.shape = (2*3, 4, 2, 3, 4)
arr2 = np.random.randn(2*3, 4)
# Display the arrays
print("Array1...\n",arr1)
print("\nArray2...\n",arr2)
# Check the Dimensions of both the arrays
print("\nDimensions of Array1...\n",arr1.ndim)
print("\nDimensions of Array2...\n",arr2.ndim)
# Check the Shape of both the arrays
print("\nShape of Array1...\n",arr1.shape)
print("\nShape of Array2...\n",arr2.shape)
# To solve the tensor equation, use the numpy.linalg.tensorsolve() method in Python.
print("\nResult...\n",np.linalg.tensorsolve(arr1, arr2))輸出
Array1... [[[[[1. 0. 0. 0.]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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]] 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]]]
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP