使用 Einstein 求和約定進行標量乘法的 Python
若要使用 Einstein 求和約定執行標量乘法,請在 Python 中使用 numpy.einsum() 方法。第 1 個引數是下標。它將逗號分隔的下標標籤列表指定為求和的下標。第 2 個引數是運算元。這些是用於操作的陣列。
einsum() 方法對運算元評估 Einstein 求和約定。使用 Einstein 求和約定,可以用簡單方式表示許多常見的多維線性代數陣列操作。在隱式模式下,einsum 會計算這些值。在顯式模式下,einsum 提供更靈活的方式來計算其他可能不被視為經典 Einstein 求和操作的陣列操作,方法是停用或強制對指定下標標籤求和。
步驟
首先,匯入需要的庫 −
import numpy as np
使用 numpy.arange() 和 reshape() 建立一個數組 −
arr = np.arange(6).reshape(2,3)
val 是標量 −
val = 2
顯示陣列 −
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)若要使用 Einstein 求和約定執行標量乘法,請使用 numpy.einsum() 方法 −
print("\nResult (scalar multiplication)...\n",np.einsum('..., ...', val, arr))
示例
import numpy as np
# Create an array using the numpy.arange() and reshape()
arr = np.arange(6).reshape(2,3)
# The val is the scalar
val = 2
# Display the array
print("Array...\n",arr)
# Check the datatype
print("\nDatatype of Array...\n",arr.dtype)
# Check the Dimension
print("\nDimensions of Array...\n",arr.ndim)
# Check the Shape
print("\nShape of Array...\n",arr.shape)
# To perform scalar multiplication with Einstein summation convention, use the numpy.einsum() method in Python.
print("\nResult (scalar multiplication)...\n",np.einsum('..., ...', val, arr))輸出
Array... [[0 1 2] [3 4 5]] Datatype of Array... int64 Dimensions of Array... 2 Shape of Array... (2, 3) Result (scalar multiplication)... [[ 0 2 4] [ 6 8 10]]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP