先看一下它的參數:
norm(p='fro', dim=None, keepdim=False, dtype=None)
- p: the order of norm. 一般來說指定 $p = 1, 2$ 等值表示 $(\sum_{i} \left | x_i \right |^{p})^{(1/p)}$,更詳細的描述可以參考:
- dim: 縮減的維度,dim=0 是對 0 維度上的一個向量求范數,返回結果數量等於其列的個數,也就是說有多少個0維度的向量, 將得到多少個范數。dim=1同理。
- keepdim: 保持輸出的維度。當 keepdim=False 時,輸出比輸入少一個維度(就是 dim 所指定的那一個被縮減的維度)。
- dtype: 用以指定結果 tensor 的數據類型。
參考以下示例代碼:
x = torch.tensor([[-1.0, 2.0, 3.0], [3.5, -4.0, 1.0]])
print(x, x.dtype) a = x.norm(1, dim=0, dtype=torch.float64) print(a, a.dtype) b = x.norm(1, dim=1) print(b, b.dtype) c = x.norm(2, dim=1) print(c, c.dtype)
結果:
tensor([[-1.0000, 2.0000, 3.0000],
[ 3.5000, -4.0000, 1.0000]]) torch.float32 tensor([4.5000, 6.0000, 4.0000], dtype=torch.float64) torch.float64 tensor([6.0000, 8.5000]) torch.float32 tensor([3.7417, 5.4083]) torch.float32