可参考 官方文档torch.norm
一、具体用法
功能:对输入的Tensor求范数;
①
torch.norm(input, p=2)
→ float
- 参数:
– input (Tensor) – 输入张量
– p (float,optional) – 范数计算中的幂指数值
②
torch.norm(input, p, dim, out=None)
→ Tensor
- 参数:
– input (Tensor) – 输入张量
– p (float) – 范数计算中的幂指数值
– dim (int) – 缩减的维度
– out (Tensor, optional) – 结果张量
二、示例
import torch
a = torch.randn(1, 3)
print(a)
print(torch.norm(a,2)) #求得2-范数
Out:
import torch
import torch.tensor as tensor
a = tensor([[1, 2, 3, 4],
[1, 2, 3, 4]]).float() #norm仅支持floatTensor,a是一个2*4的Tensor
a0 = torch.norm(a,p=2,dim=0) #按0维度求2范数
a1 = torch.norm(a,p=2,dim=1) #按1维度求2范数
print(a0)
print(a1)
Out: