归一化的方法

image-20221102120054647

Batch Norm

  • 按照不同的通道进行批归一化;
  • 比如输入是【2,3,4,5】,输入两张三通道的图像,取这两张图像的第一个通道组合起来做一次归一化,取这两张图像的第二个通道组合起来做一次归一化……
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import torch

x = torch.randn([2, 3, 2, 2])
bn = torch.nn.BatchNorm2d(3)
res = bn(x)
res1 = res[:, 0, ...]
print(res1)

x1 = x[:, 0, ...]
u = x1.mean()
s = (x1-u).pow(2).mean()
res2 = (x1-u)/torch.sqrt(s+1e-5)
print(res2)
# res1 == res2

Layer Norm

image-20221102122020184

假设我们的输入为(1, 3, 5, 5)的变量,并对其进行LayerNorm,一般来说有两种归一化的方式。如下图所示,左边为第一种归一化方法,对所有channel所有像素计算;右边为第二种归一化方法,对所有channel的每个像素分别计算

  • 计算一个batch中所有channel中所有参数的均值和方差,然后进行归一化,即(3, 5, 5)
  • 计算一个batch中所有channel中的每一个参数的均值和方差进行归一化,即(3, 1, 1),计算25次

参考