在 Python 中使用爱因斯坦求和约定计算矩阵转置


einsum() 方法计算了操作数上的爱因斯坦求和约定。使用爱因斯坦求和约定,许多常见的多维线性代数数组操作都可以用简单的方式表示。在隐式模式下,einsum 会计算这些值。在显式模式下,einsum 提供了进一步的灵活性,可以通过禁用或强制对指定下标标签求和来计算其他可能不被认为是经典爱因斯坦求和操作的数组操作。

若要使用爱因斯坦求和约定计算矩阵转置,请在 Python 中使用 numpy.einsum() 方法。第 1 个参数是下标。它将求和的下标指定为逗号分隔的下标标签列表。第 2 个参数是操作数。这些是用于该操作的数组。

步骤

首先,导入所需的库 -

import numpy as np

使用 arange() 和 reshape() 方法创建一个 numpy 数组 -

arr = np.arange(16).reshape(4,4)

显示该数组 -

print("Our Array...
",arr)

检查维度 -

print("
Dimensions of our Array...
",arr.ndim)

获取数据类型 -

print("
Datatype of our Array object...
",arr.dtype)

获取形状 -

print("
Shape of our Array object...
",arr.shape)

若要使用爱因斯坦求和约定计算矩阵转置,请在 Python 中使用 numpy.einsum() 方法 -

print("
Result (transpose)...
",np.einsum('ji', arr))

示例

import numpy as np

# Creating a numpy array using the arange() and reshape() method
arr = np.arange(16).reshape(4,4)

# Display the array
print("Our Array...
",arr) # Check the Dimensions print("
Dimensions of our Array...
",arr.ndim) # Get the Datatype print("
Datatype of our Array object...
",arr.dtype) # Get the Shape print("
Shape of our Array object...
",arr.shape) # To compute a matrix transpose with Einstein summation convention, use the numpy.einsum() method in Python. print("
Result (transpose)...
",np.einsum('ji', arr))

输出

Our Array...
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]

Dimensions of our Array...
2

Datatype of our Array object...
int64

Shape of our Array object...
(4, 4)

Result (transpose)...
[[ 0 4 8 12]
[ 1 5 9 13]
[ 2 6 10 14]
[ 3 7 11 15]]

更新日期:28-2-2022

260 篇浏览

Kickstart Your 职业生涯

完成课程获得认证

立即开始
广告
© . All rights reserved.