帶愛因斯坦求和約定的 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...\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)
對於帶有愛因斯坦求和約定的陣列軸求和(沿軸求和),在 Python 中使用 numpy.einsum() 方法 −
print("\nResult...\n",np.einsum('ij->i', 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...\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) # For Array axis summations (sum over an axis) with Einstein summation convention, use the numpy.einsum() method in Python. print("\nResult...\n",np.einsum('ij->i', 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... [ 6 22 38 54]
廣告