numpy中求解范数(numpy.linalg.norm)以及各阶范数详解

时间:2024-04-11 11:59:07

numpy.linalg.norm

语法

numpy.linalg.norm(x,ord=None,axis=None,keepdims=False)

Parameters

  • x: array_like

Input array. If axis is None, x must be 1-D or 2-D, unless ord is None. If both axis and ord are None, the 2-norm of x.ravel will be returned.

X是输入的array, array的情况必须是以下三种情况之一:

  1. axis未指定,ord指定。此时x必须是一维或二维数组
  2. axis指定,x任意
  3. axis未指定,ord未指定,此时x任意,返回值为x被展平后的一维向量x.ravel的二范数。
  • ord:{non-zero int, inf, -inf, ‘fro’, ‘nuc’}, optional

Order of the norm (see table under Notes). inf means numpy’s inf object. The default is None.

范数的阶数,可以不指定。默认为None。inf代表无穷大,-inf为无穷小。
可选的阶数见下图:

numpy中求解范数(numpy.linalg.norm)以及各阶范数详解

  • axis:{None, int, 2-tuple of ints},optional

If axis is an integer, it specifies the axis of x along which to compute the vector norms. If axis is a 2-tuple, it specifies the axes that hold 2-D matrices, and the matrix norms of these matrices are computed. If axis is None then either a vector norm (when x is 1-D) or a matrix norm (when x is 2-D) is returned. The default is None.

如果axis是整数,指定了一个维度,在该维度上按照向量进行范数计算。如果是一个二元整数组,指定了两个维度,在指定的这两个维度上可以构成矩阵。对这些矩阵进行计算。如果没有指定axis,那么对于一维输入返回其向量形式的范数计算值,对于二维输入返回其矩阵形式的范数。默认值为None

  • keepdims: bool, optional

If this is set to True, the axes which are normed over are left in the result as dimensions with size one. With this option the result will broadcast correctly against the original x.

如果keepdims=True,被指定计算范数的维度将在返回结果中保留,其size为1。计算结果会在该维度上进行broadcast

各范数详析

NOTE: 对于ord<1的各个范数,结果在严格意义不等于数学意义上的范数。但在数值计算层面仍然有效。
numpy中求解范数(numpy.linalg.norm)以及各阶范数详解

默认情况

当不指定ord时,即ord = None,对于矩阵,计算其Frobenius norm,对于向量,计算其2-norm

Frobenius范数

ord = 'fro'
其公式为:
numpy中求解范数(numpy.linalg.norm)以及各阶范数详解

F范数只对矩阵存在。其值为对所有元素的绝对值的平方求和后开平方。

Nuclear范数(核范数)

ord = 'nuc'
只对矩阵存在,矩阵的核范数等于其所有奇异值的和。

无穷大范数

对于矩阵:max(sum(abs(x), axis=1)) ,每一行最终得到一个数,返回最大的数。
对于向量:max(abs(x)

无穷小范数

对于矩阵: min(sum(abs(x),axis=1)),每一行得到一个数,返回最小的数。
对于向量: min(abs(x))

0 范数

对于矩阵:不存在
对于向量:sum(x!=0) 所有非零元素的和

1 范数

对于矩阵:max(sum(abs(x)),axis=0,每一列得到一个数,返回最大值。
对于向量:sum(abs(x)**ord)**(1./ord)

-1 范数

对于矩阵:min(sum(abs(x)),axis=0,每一列得到一个数,返回最小值。
对于向量:sum(abs(x)**ord)**(1./ord)

2 范数

对于矩阵:最大的奇异值
对于向量:sum(abs(x)**ord)**(1./ord)

-2范数

对于矩阵:最小的奇异值
对于向量:sum(abs(x)**ord)**(1./ord)

其余int值对应的范数

对于矩阵: Undefined
对于向量:sum(abs(x)**ord)**(1./ord)