Python線性代數中計算向量沿指定軸的範數


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

第三個引數axis,如果為整數,則指定沿其計算向量範數的x軸。如果axis是一個2元組,則它指定儲存二維矩陣的軸,並計算這些矩陣的矩陣範數。如果axis為None,則返回向量範數(當x是一維時)或矩陣範數(當x是二維時)。預設為None。

第四個引數keepdims,如果設定為True,則對準其進行歸一化的軸將作為大小為一的維度保留在結果中。使用此選項,結果將針對原始x正確廣播。

步驟

首先,匯入所需的庫:

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)

在Python NumPy中,使用LA.norm()方法可以返回線性代數中矩陣或向量的範數:

print("\nResult...\n",LA.norm(arr, np.inf))

示例

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, np.inf))

輸出

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.0

更新於:2022年3月2日

92次瀏覽

啟動你的職業生涯

完成課程獲得認證

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