在 Python 中获取四维数组的逆矩阵
要计算四维数组的逆矩阵,可以使用 Python 中的 numpy.linalg.tensorinv() 方法。结果是相对于 tensordot 操作 tensordot(a, b, ind) 的 a 的逆矩阵,即在浮点精度范围内,tensordot(tensorinv(a), a, ind) 是 tensordot 操作的“单位”张量。
该方法返回 a 的 tensordot 逆矩阵,形状为 a.shape[ind:] + a.shape[:ind]。第一个参数是 a,要“反转”的张量。其形状必须是“正方形”,即 prod(a.shape[:ind]) == prod(a.shape[ind:])。第二个参数是 ind,参与逆和运算的前几个索引的个数。必须是正整数,默认为 2。
步骤
首先,导入所需的库 -
import numpy as np from numpy.linalg import inv
创建一个数组。numpy.eye() 返回一个二维数组,对角线上的元素为 1,其他位置的元素为 0 -
arr = np.eye(4*6)
更改上面创建的数组的形状 -
arr.shape = (4, 6, 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)
要计算四维数组的逆矩阵,可以使用 Python 中的 numpy.linalg.tensorinv() 方法 -
print("\nResult...\n",np.linalg.tensorinv(arr))
示例
import numpy as np from numpy.linalg import inv # Create an array # The numpy.eye() returns a 2-D array with ones on the diagonal and zeros elsewhere arr = np.eye(4*6) # Changing the shape of the array created above arr.shape = (4, 6, 8, 3) # Display the array print("Our Array...\n",arr) # Check the Dimensions print("\nDimensions of our Array...\n",arr.ndim) # Get the Datatype print("\nDatatype of our Array object...\n",arr.dtype) # Get the Shape print("\nShape of our Array object...\n",arr.shape) # To compute the inverse of a Four-Dimensional array, use the numpy.linalg.tensorinv() method in Python. print("\nResult...\n",np.linalg.tensorinv(arr))
输出
Our Array... [[[[1. 0. 0.] [0. 0. 0.] [0. 0. 0.] [0. 0. 0.] [0. 0. 0.] [0. 0. 0.] [0. 0. 0.] [0. 0. 0.]] [[0. 1. 0.] [0. 0. 0.] [0. 0. 0.] [0. 0. 0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. 0. 0.] [0. 0. 0.] [0. 0. 0.] [0. 0. 0.] [0. 0. 1.] [0. 0. 0.] [0. 0. 0.] [0. 0. 0.]] [[0. 0. 0.] [0. 0. 0.] [0. 0. 0.] [0. 0. 0.] [0. 0. 0.] [1. 0. 0.] [0. 0. 0.] [0. 0. 0.]] [[0. 0. 0.] [0. 0. 0.] [0. 0. 0.] [0. 0. 0.] [0. 0. 0.] [0. 1. 0.] [0. 0. 0.] [0. 0. 0.]] [[0. 0. 0.] [0. 0. 0.] [0. 0. 0.] [0. 0. 0.] [0. 0. 0.] [0. 0. 1.] [0. 0. 0.] [0. 0. 0.]]] [[[0. 0. 0.] [0. 0. 0.] [0. 0. 0.] [0. 0. 0.] [0. 0. 0.] [0. 0. 0.] [1. 0. 0.] [0. 0. 0.]] [[0. 0. 0.] [0. 0. 0.] [0. 0. 0.] [0. 0. 0.] [0. 0. 0.] [0. 0. 0.] [0. 1. 0.] [0. 0. 0.]] [[0. 0. 0.] [0. 0. 0.] [0. 0. 0.] [0. 0. 0.] [0. 0. 0.] [0. 0. 0.] [0. 0. 1.] [0. 0. 0.]] [[0. 0. 0.] [0. 0. 0.] [0. 0. 0.] [0. 0. 0.] [0. 0. 0.] [0. 0. 0.] [0. 0. 0.] [1. 0. 0.]] [[0. 0. 0.] [0. 0. 0.] [0. 0. 0.] [0. 0. 0.] [0. 0. 0.] [0. 0. 0.] [0. 0. 0.] [0. 1. 0.]] [[0. 0. 0.] [0. 0. 0.] [0. 0. 0.] [0. 0. 0.] [0. 0. 0.] [0. 0. 0.] [0. 0. 0.] [0. 0. 1.]]]] Dimensions of our Array... 4 Datatype of our Array object... float64 Shape of our Array object... (4, 6, 8, 3) Result... [[[[1. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0.]] [[0. 1. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0.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