天天看点

pytorch函数之torch.nn.functional.normalize()

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]]])
 
           

继续阅读