在 Python 中使用爱因斯坦求和约定进行标量乘法
pythonnumpyserver side programmingprogramming更新于 2024/5/14 15:08:17
要使用爱因斯坦求和约定进行标量乘法,请使用 Python 中的 numpy.einsum() 方法。第一个参数是下标。它将求和的下标指定为以逗号分隔的下标标签列表。第二个参数是操作数。这些是用于操作的数组。
einsum() 方法评估操作数上的爱因斯坦求和约定。使用爱因斯坦求和约定,许多常见的多维线性代数数组运算可以以简单的方式表示。在隐式模式下,einsum 计算这些值。在显式模式下,einsum 通过禁用或强制对指定下标标签求和,提供了进一步的灵活性来计算可能不被视为经典爱因斯坦求和运算的其他数组运算。
步骤
首先,导入所需的库 −
import numpy as np
使用 numpy.arange() 和 reshape() 创建数组 −
arr = np.arange(6).reshape(2,3)
The val is the scalar −
val = 2
显示数组 −
print("我们的数组...\n",arr)
检查维度 −
print("\n数组的维度...\n",arr.ndim)
获取数据类型 −
print("\n我们的数组对象的数据类型...\n",arr.dtype)
获取形状 −
print("\n我们的数组对象的形状...\n",arr.shape)
要使用爱因斯坦求和约定执行标量乘法,请使用 numpy.einsum() 方法 −
print("\nResult (scalar multiplication)...\n",np.einsum('..., ...', val, arr))
示例
import numpy as np
# 使用 numpy.arange() 和 reshape() 创建数组
arr = np.arange(6).reshape(2,3)
# val 是标量
val = 2
# 显示数组
print("数组...\n",arr)
# 检查数据类型
print("\nDatatype of Array...\n",arr.dtype)
# 检查维度
print("\nDimensions of Array...\n",arr.ndim)
# 检查形状
print("\nShape of Array...\n",arr.shape)
# 要使用爱因斯坦求和约定执行标量乘法,请使用 Python 中的 numpy.einsum() 方法。
print("\nResult (scalar multiplication)...\n",np.einsum('..., ...', val, arr))
输出
数组... [[0 1 2] [3 4 5]] 数组的数据类型... int64 Dimensions of Array... 2 Shape of Array... (2, 3) Result (scalar multiplication)... [[ 0 2 4] [ 6 8 10]]
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

