Python中使用愛因斯坦求和約定進行張量收縮
對於使用愛因斯坦求和約定的張量收縮,請在Python中使用numpy.einsum()方法。第一個引數是下標,它指定用於求和的下標,以逗號分隔的下標標籤列表表示。第二個引數是運算元,即操作的陣列。
einsum()方法對運算元評估愛因斯坦求和約定。使用愛因斯坦求和約定,許多常見的多分量線性代數陣列操作可以以簡單的方式表示。在隱式模式下,einsum計算這些值。
在顯式模式下,einsum透過停用或強制對指定的下標標籤進行求和,提供了進一步的靈活性來計算可能不被認為是經典愛因斯坦求和運算的其他陣列運算。
步驟
首先,匯入所需的庫:
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.]]
廣告