在 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]]
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP