Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การคูณเวกเตอร์เมทริกซ์ด้วยแบบแผนการบวกของ Einstein ใน Python


สำหรับการคูณ Matrix Vector ด้วยหลักการบวกของ Einstein ให้ใช้เมธอด numpy.einsum() ใน Python พารามิเตอร์ที่ 1 คือตัวห้อย ระบุรายการย่อยสำหรับการรวม ascomma แยกรายการป้ายห้อย พารามิเตอร์ที่ 2 คือตัวถูกดำเนินการ นี่คืออาร์เรย์สำหรับการดำเนินการ

einsum() วิธีการประเมินแบบแผนการบวกของ Einstein บนตัวถูกดำเนินการ ด้วยการใช้แบบแผนการบวกของไอน์สไตน์ การดำเนินการอาร์เรย์เกี่ยวกับพีชคณิตเชิงเส้นหลายมิติทั่วไปจำนวนมากสามารถแสดงในรูปแบบที่เรียบง่าย ในโหมดโดยนัย einsum จะคำนวณค่าเหล่านี้

ในโหมดที่ชัดเจน einsum ให้ความยืดหยุ่นเพิ่มเติมในการคำนวณการดำเนินการอาร์เรย์อื่นๆ ที่อาจไม่ได้รับการพิจารณาว่าเป็นการดำเนินการรวมของ Einstein แบบคลาสสิก โดยการปิดใช้งาน หรือบังคับให้การรวมเกินป้ายกำกับตัวห้อย

ขั้นตอน

ขั้นแรก นำเข้าไลบรารีที่จำเป็น -

import numpy as np

การสร้างอาร์เรย์หนึ่งมิติจำนวนสองอันโดยใช้เมธอด array() -

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)

สำหรับการคูณเมทริกซ์เวกเตอร์ด้วยหลักการบวกของ Einstein ให้ใช้เมธอด numpy.einsum() ใน Python -

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]