Python 中使用愛因斯坦求和約定進行矩陣向量乘法


對於使用愛因斯坦求和約定的矩陣向量乘法,請在 Python 中使用 numpy.einsum() 方法。第一個引數是下標。它指定用於求和的下標,作為逗號分隔的下標標籤列表。第二個引數是運算元。這些是操作的陣列。

einsum() 方法對運算元評估愛因斯坦求和約定。使用愛因斯坦求和約定,許多常見的多分量線性代數陣列運算可以用簡單的方式表示。在隱式模式下,einsum 計算這些值。

在顯式模式下,einsum 透過停用或強制對指定下標標籤進行求和,提供了進一步的靈活性來計算可能不被視為經典愛因斯坦求和運算的其他陣列運算。

步驟

首先,匯入所需的庫 -

import numpy as np

使用 array() 方法建立兩個 numpy 一維陣列 -

arr1 = np.arange(25).reshape(5,5)
arr2 = np.arange(5)

顯示陣列 -

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 (Matrix Vector multiplication)...\n",np.einsum('ij,j', arr1, arr2))

示例

import numpy as np

# Creating two numpy One-Dimensional array using the array() method
arr1 = np.arange(25).reshape(5,5)
arr2 = np.arange(5)

# 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 Matrix Vector multiplication with Einstein summation convention, use the numpy.einsum() method in Python.
print("\nResult (Matrix Vector multiplication)...\n",np.einsum('ij,j', 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]]

Array2...
[0 1 2 3 4]

Dimensions of Array1...
2

Dimensions of Array2...
1

Shape of Array1...
(5, 5)

Shape of Array2...
(5,)

Result (Matrix Vector multiplication)...
[ 30 80 130 180 230]

更新於: 2022-03-02

556 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告