mindspore.mint.linalg.norm

mindspore.mint.linalg.norm(A, ord=None, dim=None, keepdim=False, *, dtype=None)[source]

Returns the matrix norm or vector norm of a given tensor.

ord is the calculation mode of norm. The following norm modes are supported.

ord

norm for matrices

norm for vectors

None (default)

Frobenius norm

2-norm (see below)

'fro'

Frobenius norm

– not supported –

'nuc'

nuclear norm

– not supported –

inf

\(max(sum(abs(x), dim=1))\)

\(max(abs(x))\)

-inf

\(min(sum(abs(x), dim=1))\)

\(min(abs(x))\)

0

– not supported –

\(sum(x != 0)\)

1

\(max(sum(abs(x), dim=0))\)

as below

-1

\(min(sum(abs(x), dim=0))\)

as below

2

largest singular value

as below

-2

smallest singular value

as below

other int or float

– not supported –

\(sum(abs(x)^{ord})^{(1 / ord)}\)

Warning

This is an experimental API that is subject to change or deletion.

Parameters
  • A (Tensor) – Tensor of shape \((*, n)\) or \((*, m, n)\) where * is zero or more batch dimensions.

  • ord (Union[int, float, inf, -inf, 'fro', 'nuc'], optional) – norm's mode. refer to the table above for behavior. Default: None .

  • dim (Union[int, Tuple(int)], optional) –

    calculate the dimension of vector norm or matrix norm. Default: None .

    • When dim is int, it will be calculated by vector norm.

    • When dim is a 2-tuple, it will be calculated by matrix norm.

    • If dim is None and ord is None, A will be flattened to 1D and the 2-norm of the vector will be calculated.

    • If dim is None and ord is not None, A must be 1D or 2D.

  • keepdim (bool) – whether the output Tensor retains the original dimension. Default: False .

Keyword Arguments

dtype (mindspore.dtype, optional) – When set, A will be converted to the specified type, dtype, before execution, and dtype of returned Tensor will also be dtype. Default: None .

Returns

Tensor, the result of norm calculation on the specified dimension, dim, has the same dtype as A.

Raises
  • ValueError – If dim is out of range.

  • TypeError – If dim is neither an int nor a tuple of int.

  • TypeError – If A is a vector and ord is a str.

  • ValueError – If A is a matrices and ord is not in valid mode.

  • ValueError – If two elements of dim is same after normalize.

  • ValueError – If any elements of dim is out of range.

Note

Dynamic shape, Dynamic rank and mutable input is not supported in graph mode (mode=mindspore.GRAPH_MODE).

Supported Platforms:

Ascend

Examples

>>> import mindspore as ms
>>> from mindspore import mint
>>> data_range = ops.arange(-13, 13, dtype=ms.float32)
>>> x = data_range[data_range != 0]
>>> print(mint.linalg.norm(x))
38.327538
>>> print(mint.linalg.norm(x, 1))
169.0
>>> n = ops.arange(27, dtype=ms.float32).reshape(3, 3, 3)
>>> print(mint.linalg.norm(n, dim=(1, 2)))
[14.282857 39.76179  66.45299 ]
>>> print(mint.linalg.norm(n[0, :, :]))
14.282857
>>> print(mint.linalg.norm(n[1, :, :]))
39.76179