📜  使用 NumPy 查找矩阵或向量范数

📅  最后修改于: 2022-05-13 01:55:26.065000             🧑  作者: Mango

使用 NumPy 查找矩阵或向量范数

为了找到矩阵或向量范数,我们使用Python库 Numpy 的函数numpy.linalg.norm()。此函数根据其参数值返回七个矩阵范数之一或无限向量范数之一。

示例 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)


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)


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)


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:
16.881943016134134

上面的代码计算维度为 (1, 10) 的向量的向量范数
示例 2:

蟒蛇3

# 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:
沿特定轴计算矩阵范数 -

蟒蛇3

# 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:

蟒蛇3

# 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

从上面的输出中,很明显我们是否将向量转换为矩阵,或者如果两者具有相同的元素,那么它们的范数也将相等。