PyTorch torch.norm function
PyTorch torch reference manual
torch.norm is a function in PyTorch that returns the norm of a tensor. By default, it computes the L2 norm (Euclidean norm).
Function definition
torch.norm(input, p='fro', dim, keepdim=False)
Usage examples
Example
import
torch
x
=
torch.
tensor
(
[
3.0
,
4.0
]
)
L2 norm (default)
(
"L2 norm:"
,
torch.
norm
(
x
)
)
L1 norm
(
"L1 norm:"
,
torch.
norm
(
x
,
p
=
1
)
)
L2 norm (using dim)
y
=
torch.
tensor
(
[
[
1.0
,
2.0
]
,
[
3.0
,
4.0
]
]
)
(
"Matrix L2 norm:"
,
torch.
norm
(
y
)
)
(
"L2 norm along dim=0:"
,
torch.
norm
(
y
,
dim
=
0
)
)
(
"L2 norm along dim=1:"
,
torch.
norm
(
y
,
dim
=
1
)
)
The output is:
L2 范数: tensor(5.)
L1 范数: tensor(7.)
矩阵 L2 范数: tensor(5.477)
按 dim=0 L2 范数: tensor([3.162, 4.472])
按 dim=1 L2 范数: tensor([2.236, 5.000])