PyTorch torch.norm Function
PyTorch torch Reference Manual
torch.normIt is a function in PyTorch used to return 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 Example
Example
import torch
x = torch.tensor([3.0, 4.0])
# L2 norm (default)
print("L2 norm:", torch.norm(x))
# L1 norm
print("L1 norm:", torch.norm(x, p=1))
# L2 norm (using dim)
y = torch.tensor([[1.0, 2.0], [3.0, 4.0]])
print("Matrix L2 norm:", torch.norm(y))
print("L2 norm along dim=0:", torch.norm(y, dim=0))
print("L2 norm along dim=1:", torch.norm(y, dim=1))
x = torch.tensor([3.0, 4.0])
# L2 norm (default)
print("L2 norm:", torch.norm(x))
# L1 norm
print("L1 norm:", torch.norm(x, p=1))
# L2 norm (using dim)
y = torch.tensor([[1.0, 2.0], [3.0, 4.0]])
print("Matrix L2 norm:", torch.norm(y))
print("L2 norm along dim=0:", torch.norm(y, dim=0))
print("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])
Other Extensions