logo

NumPy を使用して行列またはベクトル ノルムを見つける

行列またはベクトル ノルムを見つけるには、Python ライブラリ Numpy の関数 numpy.linalg.norm() を使用します。この関数は、パラメーターの値に応じて、7 つの行列ノルムの 1 つまたは無限ベクトル ノルムの 1 つを返します。

構文: numpy.linalg.norm(x, ord=なし, axis=なし)
パラメーター:
バツ: 入力
言葉: 標準の順序
軸: なし。ベクトルまたは行列ノルムを返します。整数値の場合は、ベクトル ノルムが計算される x の軸を指定します。



例 1:

Python3








# import library> import> numpy as np> # initialize vector> vec>=> np.arange(>10>)> # compute norm of vector> vec_norm>=> np.linalg.norm(vec)> print>(>'Vector norm:'>)> print>(vec_norm)>

>

>

出力:

Vector norm: 16.881943016134134>

上記のコードは、次元 (1, 10) のベクトルのベクトル ノルムを計算します。
例 2:

Python3


キーボードにはキーが何個ありますか



# import library> import> numpy as np> # initialize matrix> mat>=> np.array([[>1>,>2>,>3>],> >[>4>,>5>,>6>]])> # compute norm of matrix> mat_norm>=> np.linalg.norm(mat)> print>(>'Matrix norm:'>)> print>(mat_norm)>

>

>

出力:

Matrix norm: 9.539392014169456>

ここで、次元 (2, 3) の行列の行列ノルムを取得します。
例 3:
特定の軸に沿って行列ノルムを計算するには –

Python3




# import library> import> numpy as np> mat>=> np.array([[>1>,>2>,>3>],> >[>4>,>5>,>6>]])> # compute matrix num along axis> mat_norm>=> np.linalg.norm(mat, axis>=> 1>)> print>(>'Matrix norm along particular axis :'>)> print>(mat_norm)>

>

>

出力:

Matrix norm along particular axis : [3.74165739 8.77496439]>

このコードは行列ノルムを生成し、出力も形状 (1, 2) の行列になります。
例 4:

Python3




# import library> import> numpy as np> # initialize vector> vec>=> np.arange(>9>)> # convert vector into matrix> mat>=> vec.reshape((>3>,>3>))> # compute norm of vector> vec_norm>=> np.linalg.norm(vec)> print>(>'Vector norm:'>)> print>(vec_norm)> # computer norm of matrix> mat_norm>=> np.linalg.norm(mat)> print>(>'Matrix norm:'>)> print>(mat_norm)>

>

>

出力:

Vector norm: 14.2828568570857 Matrix norm: 14.2828568570857>

上記の出力から、ベクトルを行列に変換するか、両方の要素が同じである場合、それらのノルムも等しくなることが明らかです。