ภาพรวม
ใช้ LA.norm() (numpy.linalg.norm) คำนวณ norm ของเมทริกซ์หรือเวกเตอร์ รองรับหลาย order (ord)
พารามิเตอร์
x: อาร์เรย์อินพุท (1-D หรือ 2-D ถ้า axis=None)ord(optional): order ของ norm (default None = 2-norm สำหรับ vector, Frobenius สำหรับ matrix)axis(optional): axis สำหรับ vector norms หรือ axes สำหรับ matrix normskeepdims(optional): เก็บ dimensions ที่ norm ไว้ (default False)
ขั้นตอนการทำงาน
1. นำเข้าไลบรารี
import numpy as np from numpy import linalg as LA
2. สร้างเมทริกซ์ 2x3
arr = np.array([[1, 2, 3], [-1, 1, 4]])
3. แสดงข้อมูลเมทริกซ์
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)
4. คำนวณ norm (default = Frobenius norm สำหรับ matrix)
print("\nResult...\n", LA.norm(arr))
ตัวอย่างโค้ดเต็ม
import numpy as np
from numpy import linalg as LA
arr = np.array([[1, 2, 3], [-1, 1, 4]])
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))
ผลลัพธ์
Our Array... [[ 1 2 3] [-1 1 4]] Dimensions of our Array... 2 Datatype of our Array object... int64 Shape of our Array object... (2, 3) Result... 5.656854249492381
คำอธิบาย: Default norm สำหรับ matrix คือ Frobenius norm = √(1²+2²+3²+(-1)²+1²+4²) = √(1+4+9+1+1+16) = √32 ≈ 5.657