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

การหาผลคูณนอก (outer product) ของเวกเตอร์ด้วย Einstein summation convention ใน Python


ภาพรวม

ใช้ numpy.einsum() เพื่อคำนวณ outer product ของเวกเตอร์ ตาม Einstein summation convention โดยใช้ subscript 'i,j'

ขั้นตอนการทำงาน

  1. นำเข้าไลบรารี
    import numpy as np
    
  2. สร้างอาร์เรย์
    arr = np.arange(5)
    
  3. ตรวจสอบคุณสมบัติอาร์เรย์
    print("อาร์เรย์ของเรา...\n", arr)
    print("\nมิติ...\n", arr.ndim)
    print("\nชนิดข้อมูล...\n", arr.dtype)
    print("\nรูปร่าง...\n", arr.shape)
    
  4. คำนวณ outer product
    print("\nผลลัพธ์ (outer product)...\n", np.einsum('i,j', np.arange(2)+1, arr))
    

ตัวอย่างโค้ดสมบูรณ์

import numpy as np

arr = np.arange(5)
print("อาร์เรย์ของเรา...\n", arr)
print("\nมิติของอาร์เรย์...\n", arr.ndim)
print("\nชนิดข้อมูลของอาร์เรย์...\n", arr.dtype)
print("\nรูปร่างของอาร์เรย์...\n", arr.shape)

print("\nผลลัพธ์ (outer product)...\n", np.einsum('i,j', np.arange(2)+1, arr))

ผลลัพธ์ที่คาดหวัง

อาร์เรย์ของเรา...
 [0 1 2 3 4]
มิติของอาร์เรย์...
 1
ชนิดข้อมูลของอาร์เรย์...
 int64
รูปร่างของอาร์เรย์...
 (5,)
ผลลัพธ์ (outer product)...
 [[0 1 2 3 4]
 [0 2 4 6 8]]