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

คืนค่า Norm ของเมทริกซ์บนแกนที่กำหนดในพีชคณิตเชิงเส้นด้วย Python


บทนำ

การคืนค่า Norm ของเมทริกซ์หรือเวกเตอร์ในพีชคณิตเชิงเส้น ใช้เมธอด LA.norm() ใน NumPy พารามิเตอร์ axis ระบุแกนที่คำนวณ vector norms หรือ axes ที่เก็บเมทริกซ์ 2-D สำหรับ matrix norms

พารามิเตอร์

  • x: อาร์เรย์อินพุต
  • ord: ออเดอร์ของ norm
  • axis: integer = แกนสำหรับ vector norms, 2-tuple = axes สำหรับ matrix norms, None = vector norm (1-D) หรือ matrix norm (2-D)
  • keepdims: True = เก็บมิติที่ norm ไว้ในผลลัพธ์

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

1. นำเข้าไลบรารี

import numpy as np
from numpy import linalg as LA

2. สร้างอาร์เรย์ 3 มิติ

arr = np.arange(8).reshape(2, 2, 2)

3. แสดงอาร์เรย์

print("Our Array...\n", arr)

4. ตรวจสอบมิติ

print("\nDimensions of our Array...\n", arr.ndim)

5. ตรวจสอบชนิดข้อมูล

print("\nDatatype of our Array object...\n", arr.dtype)

6. ตรวจสอบรูปร่าง

print("\nShape of our Array object...\n", arr.shape)

7. คำนวณ Norm บน axis=(1,2)

print("\nResult...\n", LA.norm(arr, axis=(1, 2)))

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

import numpy as np
from numpy import linalg as LA

arr = np.arange(8).reshape(2, 2, 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)
print("\nResult...\n", LA.norm(arr, axis=(1, 2)))

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

Our Array...   [[[0 1] [2 3]] [[4 5] [6 7]]]
Dimensions of our Array... 3
Datatype of our Array object... int64
Shape of our Array object... (2, 2, 2)
Result...   [ 3.74165739 11.22497216]