在Python中计算不同维度数组在特定轴上的张量点积
给定两个张量 a 和 b,以及一个包含两个类数组对象的类数组对象 (a_axes, b_axes),在由 a_axes 和 b_axes 指定的轴上对 a 和 b 的元素(分量)的乘积求和。第三个参数可以是一个单一的非负整数型标量 N;如果是这样,则对 a 的最后 N 维和 b 的前 N 维求和。
要计算不同维度数组的张量点积,可以使用 Python 中的 numpy.tensordot() 方法。参数 a、b 是要“点乘”的张量。
参数 axes,整数型:如果为整数 N,则按顺序对 a 的最后 N 个轴和 b 的前 N 个轴求和。对应轴的大小必须匹配。
步骤
首先,导入所需的库:
import numpy as np
使用 array() 方法创建两个不同维度的 numpy 数组:
arr1 = np.array(range(1, 9)) arr1.shape = (2, 2, 2) arr2 = np.array(('p', 'q', 'r', 's'), dtype=object) arr2.shape = (2, 2)
显示数组:
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)
要计算不同维度数组的张量点积,可以使用 numpy.tensordot() 方法:
print("\nTensor dot product...\n", np.tensordot(arr1, arr2, axes = 1))
示例
import numpy as np # Creating two numpy arrays with different dimensions using the array() method arr1 = np.array(range(1, 9)) arr1.shape = (2, 2, 2) arr2 = np.array(('p', 'q', 'r', 's'), dtype=object) arr2.shape = (2, 2) # 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 compute the tensor dot product for arrays with different dimensions, use the numpy.tensordot() method in Python # The a, b parameters are Tensors to “dot”. print("\nTensor dot product...\n", np.tensordot(arr1, arr2, axes = 1))
输出
Array1... [[[1 2] [3 4]] [[5 6] [7 8]]] Array2... [['p' 'q'] ['r' 's']] Dimensions of Array1... 3 Dimensions of Array2... 2 Shape of Array1... (2, 2, 2) Shape of Array2... (2, 2) Tensor dot product... [[['prr' 'qss'] ['ppprrrr' 'qqqssss']] [['ppppprrrrrr' 'qqqqqssssss'] ['ppppppprrrrrrrr' 'qqqqqqqssssssss']]]
广告