torch.linalg.norm
- torch.linalg.norm(input, ord=None, dim=None, keepdim=False, *, out=None, dtype=
Computes a vector or matrix norm.
Supports input of float, double, cfloat and cdouble dtypes.
Whether this function computes a vector or matrix norm is determined as follows:
If dim is an int, the vector norm will be computed.
If dim is a 2-tuple, the matrix norm will be computed.
If dim= None and ord= None,
input will be flattened to 1D and the 2-norm of the resulting vector will be computed.
If dim= None and ord != None, input must be 1D or 2D.
ord defines the norm that is computed. The following norms are supported:
| norm for matrices | norm for vectors |
|---|---|---|
None (default) | Frobenius norm | 2-norm (see below) |
‘fro’ | Frobenius norm |
where inf refers to float(‘inf’), NumPy’s inf object, or any equivalent object.
input (Tensor) – tensor of shape (*, n) or (*, m, n) where * is zero or more batch dimensions
ord (int, float, inf, -inf, 'fro', 'nuc', optional) – order of norm. Default: None
dim (int, Tuple[int) – dimensions over which to compute the vector or matrix norm. See above for the behavior when . Default:
Examples:
>>> from torch import linalg as LA
>>> a = torch.arange(9, dtype=torch.float) - 4
>>> a
tensor([-4., -3., -2., -1., 0., 1., 2., 3., 4.])
>>> B = a.reshape((
Using the dim argument to compute vector norms:
>>> c = torch.tensor([[1., 2., 3.],
... [-1, 1, 4]])
>>> LA.norm(c, dim=0)
tensor([1.4142, 2.2361, 5.0000])
>>> LA
Using the dim argument to compute matrix norms:
>>> A = torch.arange(8, dtype=torch.float).reshape(2, 2, 2)
>>> LA.norm(A, dim=(1,2
– 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)} |
dimkeepdim (bool, optional) – If set to True, the reduced dimensions are retained in the result as dimensions with size one. Default: False
out (Tensor, optional) – output tensor. Ignored if None. Default: None.
dtype (torch.dtype, optional) – If specified x is cast to
dtype prior to doing the accumulation. Default: None
A real-valued tensor, even when input is complex.