maxframe.tensor.linalg.norm#

maxframe.tensor.linalg.norm(x, ord=None, axis=None, keepdims=False)[源代码]#

矩阵或向量范数。

此函数能够根据 ord 参数的值返回八种不同的矩阵范数之一,或无限多种向量范数之一(如下所述)。

参数:
  • x (array_like) -- 输入张量。如果 axis 为 None,则 x 必须是一维或二维。

  • ord ({non-zero int, inf, -inf, 'fro', 'nuc'}, optional) -- 范数的阶数(参见 Notes 下的表格)。inf 表示 maxframe 张量的 inf 对象。

  • axis ({int, 2-tuple of ints, None}, optional) -- 如果 axis 是一个整数,它指定计算向量范数时 x 的轴。如果 axis 是一个二元组,它指定包含二维矩阵的轴,并计算这些矩阵的矩阵范数。如果 axis 为 None,则返回向量范数(当 x 是一维时)或矩阵范数(当 x 是二维时)。

  • keepdims (bool, optional) -- 如果设置为 True,范数计算所涉及的轴将保留在结果中,尺寸为 1。使用此选项时,结果将可以正确地与原始 x 广播。

返回:

n -- 矩阵或向量的范数。

返回类型:

float or Tensor

备注

对于 ord <= 0 的值,严格来说结果不是数学意义上的“范数”,但对各种数值计算目的仍然可能有用。

可以计算以下范数:

阶数

矩阵范数

向量范数

Frobenius 范数

2-范数

'fro'

Frobenius 范数

--

'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))

如下所示

-1

min(sum(abs(x), axis=0))

如下所示

2

2-范数(最大奇异值)

如下所示

-2

最小奇异值

如下所示

其他

--

sum(abs(x)**ord)**(1./ord)

Frobenius 范数由 [1] 给出:

\(||A||_F = [\\sum_{i,j} abs(a_{i,j})^2]^{1/2}\)

核范数是奇异值的和。

引用

示例

>>> from maxframe.tensor import linalg as LA
>>> import maxframe.tensor as mt
>>> a = mt.arange(9) - 4
>>> a.execute()
array([-4, -3, -2, -1,  0,  1,  2,  3,  4])
>>> b = a.reshape((3, 3))
>>> b.execute()
array([[-4, -3, -2],
       [-1,  0,  1],
       [ 2,  3,  4]])
>>> LA.norm(a).execute()
7.745966692414834
>>> LA.norm(b).execute()
7.745966692414834
>>> LA.norm(b, 'fro').execute()
7.745966692414834
>>> LA.norm(a, mt.inf).execute()
4.0
>>> LA.norm(b, mt.inf).execute()
9.0
>>> LA.norm(a, -mt.inf).execute()
0.0
>>> LA.norm(b, -mt.inf).execute()
2.0
>>> LA.norm(a, 1).execute()
20.0
>>> LA.norm(b, 1).execute()
7.0
>>> LA.norm(a, -1).execute()
0.0
>>> LA.norm(b, -1).execute()
6.0
>>> LA.norm(a, 2).execute()
7.745966692414834
>>> LA.norm(b, 2).execute()
7.3484692283495345
>>> LA.norm(a, -2).execute()
0.0
>>> LA.norm(b, -2).execute()
4.351066026358965e-18
>>> LA.norm(a, 3).execute()
5.8480354764257312
>>> LA.norm(a, -3).execute()
0.0

使用 axis 参数计算向量范数:

>>> c = mt.array([[ 1, 2, 3],
...               [-1, 1, 4]])
>>> LA.norm(c, axis=0).execute()
array([ 1.41421356,  2.23606798,  5.        ])
>>> LA.norm(c, axis=1).execute()
array([ 3.74165739,  4.24264069])
>>> LA.norm(c, ord=1, axis=1).execute()
array([ 6.,  6.])

使用 axis 参数计算矩阵范数:

>>> m = mt.arange(8).reshape(2,2,2)
>>> LA.norm(m, axis=(1,2)).execute()
array([  3.74165739,  11.22497216])
>>> LA.norm(m[0, :, :]).execute(), LA.norm(m[1, :, :]).execute()
(3.7416573867739413, 11.224972160321824)