1、函數介紹
1.1 作用
- 将輸入的資料
按照指定的次元(input)
做(dim)
運算,即将某一個次元除以那個次元對應的範數。p範數(預設是2範數)
2、舉例
2.1 輸入為一維Tensor
dim=0
,可以看到每一個數字都除以了這個Tensor的2範數: 1 2 + 2 2 + 3 2 = 3.7416 \sqrt{1^{2} + 2^{2} + 3^{2}} = 3.7416 12+22+32
=3.7416
import torch
a = torch.Tensor([1, 2, 3])
print(torch.nn.functional.normalize(a, dim=0))
tensor([0.2673, 0.5345, 0.8018])
2.2 輸入為二維Tensor
-
dim=0,是對列操作。以第一列為例,整體除以了第一列的範數: 1 2 + 4 2 = 4.1231 \sqrt{1^{2}+4^{2}} = 4.1231 12+42
=4.1231
b = torch.Tensor([[1, 2, 3],
[4, 5, 6]])
print(torch.nn.functional.normalize(b, dim=0))
tensor([[0.2425, 0.3714, 0.4472],
[0.9701, 0.9285, 0.8944]])
-
dim=1,是對行操作。以第一行為例,整體除以了第一行的範數: 1 2 + 2 2 + 3 2 = 3.7416 \sqrt{1^{2} + 2^{2} + 3^{2}} = 3.7416 12+22+32
=3.7416
b = torch.Tensor([[1,2,3],
[4,5,6]])
print(torch.nn.functional.normalize(b, dim=1))
tensor([[0.2673, 0.5345, 0.8018],
[0.4558, 0.5698, 0.6838]])
2.3 輸入為三維Tensor
-
dim=2,是對第三個次元,也就是每一行操作。以第一行為例,除以第一行的2範數: 1 2 + 2 2 + 3 2 = 3.7416 \sqrt{1^{2} + 2^{2} + 3^{2}} = 3.7416 12+22+32
=3.7416
b = torch.Tensor([[[1,2,3],
[4,5,6]],
[[1,2,3],
[4,5,6]]])
torch.nn.functional.normalize(b, dim=2)
tensor([[[0.2673, 0.5345, 0.8018],
[0.4558, 0.5698, 0.6838]],
[[0.2673, 0.5345, 0.8018],
[0.4558, 0.5698, 0.6838]]])
-
dim=1,是對第二個次元操作。第二個次元是二維數組,是以此時相當于對二維數組的第0維操作。以[[1,2,3], [4,5,6]]為例,此時要對它的列操作。第一列要除以這一列的範數: 1 2 + 4 2 = 4.1231 \sqrt{1^{2}+4^{2}} = 4.1231 12+42
=4.1231
b = torch.Tensor([[[1,2,3],
[4,5,6]],
[[1,2,3],
[4,5,6]]])
torch.nn.functional.normalize(b, dim=1)
tensor([[[0.2425, 0.3714, 0.4472],
[0.9701, 0.9285, 0.8944]],
[[0.2425, 0.3714, 0.4472],
[0.9701, 0.9285, 0.8944]]])