使用 Einstein 求和约定进行标量乘法的 Python
若要使用 Einstein 求和约定执行标量乘法,请在 Python 中使用 numpy.einsum() 方法。第 1 个参数是下标。它将逗号分隔的下标标签列表指定为求和的下标。第 2 个参数是操作数。这些是用于操作的数组。
einsum() 方法对操作数评估 Einstein 求和约定。使用 Einstein 求和约定,可以用简单方式表示许多常见的多维线性代数数组操作。在隐式模式下,einsum 会计算这些值。在显式模式下,einsum 提供更灵活的方式来计算其他可能不被视为经典 Einstein 求和操作的数组操作,方法是禁用或强制对指定下标标签求和。
步骤
首先,导入需要的库 −
import numpy as np
使用 numpy.arange() 和 reshape() 创建一个数组 −
arr = np.arange(6).reshape(2,3)
val 是标量 −
val = 2
显示数组 −
print("Our Array...\n",arr)
检查维度 −
print("\nDimensions of our Array...\n",arr.ndim)获取数据类型 −
print("\nDatatype of our Array object...\n",arr.dtype)
获取形状 −
print("\nShape of our Array object...\n",arr.shape)若要使用 Einstein 求和约定执行标量乘法,请使用 numpy.einsum() 方法 −
print("\nResult (scalar multiplication)...\n",np.einsum('..., ...', val, arr))
示例
import numpy as np
# Create an array using the numpy.arange() and reshape()
arr = np.arange(6).reshape(2,3)
# The val is the scalar
val = 2
# Display the array
print("Array...\n",arr)
# Check the datatype
print("\nDatatype of Array...\n",arr.dtype)
# Check the Dimension
print("\nDimensions of Array...\n",arr.ndim)
# Check the Shape
print("\nShape of Array...\n",arr.shape)
# To perform scalar multiplication with Einstein summation convention, use the numpy.einsum() method in Python.
print("\nResult (scalar multiplication)...\n",np.einsum('..., ...', val, arr))输出
Array... [[0 1 2] [3 4 5]] Datatype of Array... int64 Dimensions of Array... 2 Shape of Array... (2, 3) Result (scalar multiplication)... [[ 0 2 4] [ 6 8 10]]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP