在Python中使用Einstein累加约定进行向量外积
要使用Einstein累加约定计算向量的外积,在Python中使用numpy.einsum()方法。第一个参数是下标,用逗号分隔的下标标签列表来指定求和下标。第二个参数是操作数,即用于操作的数组。
einsum()方法对操作数计算Einstein累加约定。使用Einstein累加约定,可以以简洁的方式表示许多常见的多维线性代数数组操作。隐式模式下,einsum计算这些值。
在显式模式下,einsum提供了进一步的灵活性,可以计算其他可能不被视为经典Einstein累加操作的数组运算,通过禁用或强制对指定下标标签进行求和。
步骤
首先,导入所需的库-
import numpy as np
使用arange()和reshape()方法创建一个numpy数组 –
arr = np.arange(5)
显示数组 –
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 (outer product)...\n",np.einsum('i,j', np.arange(2)+1, arr))
示例
import numpy as np
# Creating a numpy array using the arange() and reshape() method
arr = np.arange(5)
# Display the array
print("Our Array...\n",arr)
# Check the Dimensions
print("\nDimensions of our Array...\n",arr.ndim)
# Get the Datatype
print("\nDatatype of our Array object...\n",arr.dtype)
# Get the Shape
print("\nShape of our Array object...\n",arr.shape)
# To compute outer product of vectors with Einstein summation convention, use the numpy.einsum() method in Python.
print("\nResult (outer product)...\n",np.einsum('i,j', np.arange(2)+1, arr))
输出
Our Array...
[0 1 2 3 4]
Dimensions of our Array...
1
Datatype of our Array object...
int64
Shape of our Array object...
(5,)
Result (outer product)...
[[0 1 2 3 4]
[0 2 4 6 8]]
极客笔记