使用 Python 中的爱因斯坦求和约定进行矩阵向量乘法
pythonnumpyserver side programmingprogramming更新于 2024/5/14 14:36:17
对于使用爱因斯坦求和约定进行矩阵向量乘法,请使用 Python 中的 numpy.einsum() 方法。第一个参数是下标。它将求和的下标指定为以逗号分隔的下标标签列表。第二个参数是操作数。这些是用于操作的数组。
einsum() 方法评估操作数上的爱因斯坦求和约定。使用爱因斯坦求和约定,许多常见的多维线性代数数组运算可以以简单的方式表示。在隐式模式下,einsum 计算这些值。
在显式模式下,einsum 通过禁用或强制对指定下标标签求和,提供了进一步的灵活性来计算可能不被视为经典爱因斯坦求和运算的其他数组运算。
步骤
首先,导入所需的库 −
import numpy as np
使用 array() 方法创建两个 numpy 一维数组 −
arr1 = np.arange(25).reshape(5,5) arr2 = np.arange(5)
显示数组 −
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.einsum() 方法 −
print("\nResult (矩阵向量乘法)...\n",np.einsum('ij,j', arr1, arr2))
示例
import numpy as np
# 使用 array() 方法创建两个 numpy 一维数组
arr1 = np.arange(25).reshape(5,5)
arr2 = np.arange(5)
# 显示数组
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.einsum() 方法。
print("\n结果 (矩阵向量乘法)...\n",np.einsum('ij,j', arr1, arr2))
输出
Array1... [[ 0 1 2 3 4] [ 5 6 7 8 9] [10 11 12 13 14] [15 16 17 18 19] [20 21 22 23 24]] Array2... [0 1 2 3 4] 数组 1 的维度... 2 数组 2 的维度... 1 数组 1 的形状... (5, 5) 数组 2 的形状... (5,) 结果 (矩阵向量乘法)... [ 30 80 130 180 230]
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

