Python線性代數中矩陣的核範數計算


在Python NumPy中,使用`LA.norm()`方法可以返回線性代數中矩陣或向量的範數。第一個引數`x`是輸入陣列。如果`axis`為`None`,則`x`必須是一維或二維陣列,除非`ord`為`None`。如果`axis`和`ord`都為`None`,則返回`x.ravel`的2-範數。

第二個引數`ord`是範數的階數。`inf`表示NumPy的`inf`物件。預設值為`None`。“nuc”作為引數設定的是核範數。Frobenius範數和核範數的階數僅對矩陣定義。

步驟

首先,匯入所需的庫:

import numpy as np
from numpy import linalg as LA

建立一個數組:

arr = np.array([[ -4, -3, -2], [-1, 0, 1], [2, 3, 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)

要返回線性代數中矩陣或向量的範數,請使用`LA.norm()`方法:

print("\nResult...\n",LA.norm(arr, 'nuc'))

示例

import numpy as np
from numpy import linalg as LA

# Create an array
arr = np.array([[ -4, -3, -2],[-1, 0, 1],[2, 3, 4] ])

# Display the array
print("Our Array...\n",arr)

# Check the Dimensions
print("\nDimensions of our Array...\n",arr.ndim)

# Get the Datatype
print("\nDatatype of our Array object...\n",arr.dtype)

# Get the Shape
print("\nShape of our Array object...\n",arr.shape)

# To return the Norm of the matrix or vector in Linear Algebra, use the LA.norm() method in Python Numpy
print("\nResult...\n",LA.norm(arr, 'nuc'))

輸出

Our Array...
   [[-4 -3 -2]
   [-1 0 1]
   [ 2 3 4]]

Dimensions of our Array...
2

Datatype of our Array object...
int64

Shape of our Array object...
(3, 3)

Result...
9.797958971132713

更新於:2022年3月9日

377 次檢視

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.