在 Python 中计算 N 维数组的逆
numpyserver side programmingprogramming
要计算 N 维数组的逆,请使用 Python 中的 numpy.linalg.tensorinv() 方法。结果是相对于张量点运算 tensordot(a, b, ind) 的逆,即,在浮点精度范围内,tensordot(tensorinv(a), a, ind) 是张量点运算的"恒等"张量。
该方法返回 a 的张量点逆,形状为 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("我们的数组...
",arr)
检查维度 −
print("
我们数组的维度...
",arr.ndim)
获取数据类型 −
print("
数组对象的数据类型...
",arr.dtype)
获取形状 −
print("
数组对象的形状...
",arr.shape)
要计算 N 维数组的逆,请使用 Python 中的 numpy.linalg.tensorinv() 方法 −
print("
结果...
",np.linalg.tensorinv(arr))
示例
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("我们的数组...
",arr) # 检查维度 print("
我们数组的维度...
",arr.ndim) # 获取数据类型 print("
我们的数组对象的数据类型...
",arr.dtype) # 获取形状 print("
我们的数组对象的形状...
",arr.shape) # 要计算 N 维数组的逆,请使用 Python 中的 numpy.linalg.tensorinv() 方法。 print("
结果...
",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.] [0. 0. 0.] [0. 0. 0.] [0.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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.]]]] 数组的维度... 4 数组对象的数据类型... float64 数组对象的形状... (4, 6, 8, 3) 结果... [[[[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.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