torch.functional.norm
- torch.functional.norm(input, p='fro', dim=None, keepdim=False, out=None, dtype=
Returns the matrix norm or vector norm of a given tensor.
input (Tensor) – The input tensor. Its data type must be either a floating
point or complex type. For complex inputs, the norm is calculated using the
absolute value of each element. If the input is complex and neither
dtype nor out is specified, the result’s data type will
be the corresponding floating point type (e.g. float if input is
complexfloat).
p (int, float, inf, -inf, 'fro', 'nuc', optional) –
the order of norm. Default: 'fro'
The following norms can be calculated:
Example:
>>> import torch
>>> a = torch.arange(9, dtype= torch.float) - 4
>>> b = a.reshape((3, 3))
>>> torch.norm(
ord | matrix norm | vector norm |
|---|---|---|
’fro’ | Frobenius norm | – |
‘nuc’ | nuclear norm | – |
Number | – | sum(abs(x)**ord)**(1./ord) |
The vector norm can be calculated across any number of dimensions.
The corresponding dimensions of input are flattened into
one dimension, and the norm is calculated on the flattened
dimension.
Frobenius norm produces the same result as p=2 in all cases
except when dim is a list of three or more dims, in which
case Frobenius norm throws an error.
Nuclear norm can only be calculated across exactly two dimensions.
dim (int, tuple of ints, list of ints, optional) – Specifies which dimension or dimensions of input to
calculate the norm across. If dim is None, the norm will
be calculated across all dimensions of input. If the norm
type indicated by p does not support the specified number of
dimensions, an error will occur.
keepdim (bool, optional) – whether the output tensors have dim
retained or not. Ignored if dim = None and
out = None. Default: False
out (Tensor, optional) – the output tensor. Ignored if
dim = None and out = None.
dtype (torch.dtype, optional) – the desired data type of
returned tensor. If specified, the input tensor is casted to
dtype while performing the operation. Default: None.