PyTorch torch.linalg.norm function
PyTorch torch reference manual
torch.linalg.norm is a function in PyTorch's linear algebra module used to compute the norm of a matrix or vector. It supports many norm types, such as L1, L2, and Frobenius norms.
Function definition
torch.linalg.norm(A, ord=None, dim=None, keepdim=False, out=None, dtype=None)
Parameters:
A(Tensor): the input tensor.ord(int, float, inf, -inf, optional): Norm type. Defaults to 'fro'.dim(int, tuple, optional): Dimension along which to compute the norm.keepdim(bool, optional): Whether to keep the dimension. Defaults to False.dtype(torch.dtype, optional): Output data type.
Return Value:
torch.Tensor: Returns the norm value.
Usage examples
Example - Frobenius norm
import
torch
Create a matrix
A
=
torch.
tensor
(
[
[
1.0
,
2.0
]
,
[
3.0
,
4.0
]
]
)
Frobenius norm
norm_fro
=
torch.
linalg
.
norm
(
A
)
(
"Matrix A:"
)
(
A
)
(
"Frobenius norm:"
,
norm_fro
)
The output is:
矩阵 A:
tensor([[1., 2.],
[3., 4.]])
Frobenius 范数: tensor(5.4772)
Example - vector L2 norm
import
torch
Create a vector
v
=
torch.
tensor
(
[
3.0
,
4.0
]
)
L2 norm (default)
norm_l2
=
torch.
linalg
.
norm
(
v
)
L1 norm
norm_l1
=
torch.
linalg
.
norm
(
v
,
ord
=
1
)
(
"Vector v:"
,
v
)
(
"L2 norm:"
,
norm_l2
)
(
"L1 norm:"
,
norm_l1
)