Batch Norm和Layer Norm的区别

Batch Norm

x = torch.rand(5, 3, 5, 5) #batchsize=5 RGB图像

x1 = x.permute(1, 0, 2, 3).reshape(3, -1) # 对(N, H, W)计算均值方差
mean = x1.mean(dim=1).reshape(1, 3, 1, 1)
# x1.mean(dim=1)后维度为(3,)
std = x1.std(dim=1, unbiased=False).reshape(1, 3, 1, 1)
my_bn = (x - mean)/std
print((official_bn-my_bn).sum())  # 输出误差

x.permute(1,0,2,3)的作用是将 RGB中的R、G、B抽出来,然后将这些R、G、B放在一起


Batch Norm和Layer Norm的区别_第1张图片
变为
Batch Norm和Layer Norm的区别_第2张图片

对于permute这个函数,还是要结合()中每个参数的定义去理解

  • 比如RGB图像

    (B C H W) 其中C=3
    B就是图像的个数 C就是三个H、W的灰度图片叠在一起
    x.permute(1,0,2,3)就是C个图像、B个H W的灰度图像叠在一起
    x.permute(0,2,3,1)就是B个图、H个W C的灰度图像叠在一起
    Batch Norm和Layer Norm的区别_第3张图片
    W C就是立方体中阴影的平面

  • 比如体数据

    (B C D H W) C通常为1
      
      

Layer Norm

x = torch.rand(5, 3, 5, 5)

x1 = x.reshape(10, -1)  # 对(C,H,W)计算均值方差
mean = x1.mean(dim=1).reshape(10, 1, 1, 1)
std = x1.std(dim=1, unbiased=False).reshape(10, 1, 1, 1)
my_ln = (x - mean)/std

你可能感兴趣的:(深度学习)