Python中使用Einstein求和约定进行张量收缩

Python中使用Einstein求和约定进行张量收缩

对于使用Einstein求和约定进行张量收缩,可以使用Python中的numpy.einsum()方法。第一个参数是下标,用逗号分隔的下标标签列表指定求和的下标。第二个参数是操作数,即进行操作的数组。

einsum()方法在操作数上计算Einstein求和约定。使用Einstein求和约定可以以简单的方式表示许多常见的多维线性代数数组操作。在隐式模式下,einsum计算这些值。

在显式模式下,einsum提供了进一步的灵活性,以计算其他可能不被认为是经典的Einstein求和运算的数组操作,可以禁用或强制求和指定的下标标签。

步骤

首先,导入所需的库 –

import numpy as np

使用array()方法创建两个 numpy 一维数组 –

arr1 = np.arange(60.).reshape(3,4,5)
arr2 = np.arange(24.).reshape(4,3,2)

将数组显示出来-

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 (Tensor contraction)...\n",np.einsum('ijk,jil->kl', arr1, arr2))

示例

import numpy as np

# Creating two numpy One-Dimensional array using the array() method
arr1 = np.arange(60.).reshape(3,4,5)
arr2 = np.arange(24.).reshape(4,3,2)

# Display the arrays
print("Array1...\n",arr1)
print("\nArray2...\n",arr2)

# Check the Dimensions of both the arrays
print("\nDimensions of Array1...\n",arr1.ndim)
print("\nDimensions of Array2...\n",arr2.ndim)

# Check the Shape of both the arrays
print("\nShape of Array1...\n",arr1.shape)
print("\nShape of Array2...\n",arr2.shape)

# For Tensor contraction with Einstein summation convention, use the numpy.einsum() method in Python.
print("\nResult (Tensor contraction)...\n",np.einsum('ijk,jil->kl', 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.]
[25. 26. 27. 28. 29.]
[30. 31. 32. 33. 34.]
[35. 36. 37. 38. 39.]]

[[40. 41. 42. 43. 44.]
[45. 46. 47. 48. 49.]
[50. 51. 52. 53. 54.]
[55. 56. 57. 58. 59.]]]

Array2...
[[[ 0. 1.]
[ 2. 3.]
[ 4. 5.]]

[[ 6. 7.]
[ 8. 9.]
[10. 11.]]

[[12. 13.]
[14. 15.]
[16. 17.]]

[[18. 19.]
[20. 21.]
[22. 23.]]]

Dimensions of Array1...
3

Dimensions of Array2...
3

Shape of Array1...
(3, 4, 5)

Shape of Array2...
(4, 3, 2)

Result (Tensor contraction)...
[[4400. 4730.]
[4532. 4874.]
[4664. 5018.]
[4796. 5162.]
[4928. 5306.]]

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程