PyTorch torch.linalg.norm Function
PyTorch torch Reference Manual
torch.linalg.normIt is a function in the PyTorch linear algebra module used to compute matrix or vector norms. It supports multiple norm types, such as L1, L2, Frobenius norms, etc.
Function Definition
torch.linalg.norm(A, ord=None, dim=None, keepdim=False, out=None, dtype=None)
Parameters:
A(Tensor): Input tensor.ord(int, float, inf, -inf, optional): Norm type. Default is 'fro'.dim(int, tuple, optional): Dimensions over which to compute the norm.keepdim(bool, optional): Whether to keep the dimensions. Default is False.dtype(torch.dtype, optional): Output data type.
Return Value:
torch.Tensor: Returns the norm value.
Usage Examples
Example - Frobenius Norm
import torch
# Create matrix
A = torch.tensor([[1.0, 2.0], [3.0, 4.0]])
# Frobenius norm
norm_fro = torch.linalg.norm(A)
print("Matrix A:")
print(A)
print("Frobenius norm:", norm_fro)
# Create matrix
A = torch.tensor([[1.0, 2.0], [3.0, 4.0]])
# Frobenius norm
norm_fro = torch.linalg.norm(A)
print("Matrix A:")
print(A)
print("Frobenius norm:", norm_fro)
The output result is:
矩阵 A:
tensor([[1., 2.],
[3., 4.]])
Frobenius 范数: tensor(5.4772)
Example - Vector L2 Norm
import torch
# Create 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)
print("Vector v:", v)
print("L2 norm:", norm_l2)
print("L1 norm:", norm_l1)
# Create 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)
print("Vector v:", v)
print("L2 norm:", norm_l2)
print("L1 norm:", norm_l1)
Other Extensions