使用 Python 计算具有类似数组的轴的不同维度数组的张量点积
pythonnumpyserver side programmingprogramming更新于 2024/5/14 13:32:17
给定两个张量 a 和 b,以及一个包含两个类似数组对象的类似数组对象 (a_axes,b_axes),将 a 和 b 的元素 (分量) 在 a_axes 和 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, ((0, 1), (0, 1))))
示例
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)
# 要计算具有不同维度的数组的张量点积,请使用 Python 中的 numpy.tensordot() 方法
print("\nTensor dot product...\n", np.tensordot(arr1, arr2, ((0, 1), (0, 1))))
输出
Array1... [[[1 2] [3 4]] [[5 6] [7 8]]] Array2... [['p' 'q'] ['r' 's']] Array1 的维度... 3 Array2 的维度... 2 Array1 的形状... (2, 2, 2) Array2 的形状... (2, 2) 张量点积... ['pqqqrrrrrsssssss' 'ppqqqqrrrrrrssssssss']
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

