在 Python 中获取 3D 数组的逆
pythonnumpyserver side programmingprogramming
要计算 3D 数组的逆,请使用 Python 中的 numpy.linalg.tensorinv() 方法。结果是相对于张量点运算 tensordot(a, b, ind) 的 a 的逆,即,在浮点精度范围内,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 = (24, 8, 3)
显示数组 −
print("我们的数组...\n",arr)
检查维度 −
print("\n数组的维度...\n",arr.ndim)
获取数据类型 −
print("\n我们的数组对象的数据类型...\n",arr.dtype)
获取形状 −
print("\n我们的数组对象的形状...\n",arr.shape)
要计算三维数组的逆,请使用 Python 中的 numpy.linalg.tensorinv() 方法 −
print("\n结果...\n",np.linalg.tensorinv(arr, ind = 1))
示例
import numpy as np from numpy.linalg import inv # 创建数组 # numpy.eye() 返回一个二维数组,对角线上为 1,其他地方为 0 arr = np.eye(4*6) # 更改上面创建的数组的形状 arr.shape = (24, 8, 3) # 显示数组 print("我们的数组...\n",arr) # 检查维度 print("\n数组的维度...\n",arr.ndim) # 获取数据类型 print("\n我们的数组对象的数据类型...\n",arr.dtype) # 获取形状 print("\n我们的数组对象的形状...\n",arr.shape) # 要计算三维数组的逆,请使用 Python 中的 numpy.linalg.tensorinv() 方法。 print("\n结果...\n",np.linalg.tensorinv(arr, ind = 1))
输出
我们的数组... [[[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. 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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. 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.]]] 我们的数组的维度... 3 我们的数组对象的数据类型... float64 我们的数组对象的形状... (24, 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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