pytorch中nn模块的BatchNorm2d()函数

可以参考 https://www.cnblogs.com/king-lps/p/8378561.html
在卷积神经网络的卷积层之后总会添加BatchNorm2d进行数据的归一化处理,这使得数据在进行Relu之前不会因为数据过大而导致网络性能的不稳定,常用于卷积网络中(防止梯度消失或爆炸)。
BatchNorm2d()函数数学原理如下:
pytorch中nn模块的BatchNorm2d()函数
pytorch中nn模块的BatchNorm2d()函数
例如:假设在网络中间经过某些卷积操作之后的输出的feature map的尺寸为4×3×2×2
4为batch的大小,3为channel的数目,2×2为feature map的长宽
整个BN层的运算过程如下图
pytorch中nn模块的BatchNorm2d()函数
上图中,batch size一共是4, 对于每一个batch的feature map的size是3×2×2

对于所有batch中的同一个channel的元素进行求均值与方差,比如上图,对于所有的batch,都拿出来最后一个channel,一共有4×4=16个元素,

然后求区这16个元素的均值与方差(上图只求了mean,没有求方差。。。),

求取完了均值与方差之后,对于这16个元素中的每个元素进行减去求取得到的均值与方差,然后乘以gamma加上beta,公式如下
pytorch中nn模块的BatchNorm2d()函数
所以对于一个batch normalization层而言,求取的均值与方差是对于所有batch中的同一个channel进行求取,batch normalization中的batch体现在这个地方

batch normalization层能够学习到的参数,对于一个特定的channel而言实际上是两个参数,gamma与beta,对于total的channel而言实际上是channel数目的两倍。

用pytorch验证上述想法是否准确,用上述方法求取均值,以及用batch normalization层输出的均值,看看是否一样

上代码

from torch import nn
import torch

m = nn.BatchNorm2d(3,1) # bn设置的参数实际上是channel的参数
input = torch.randn(4, 3, 2, 2)
output = m(input)

print(output)

a = (input[0, 0, :, :]+input[1, 0, :, :]+input[2, 0, :, :]+input[3, 0, :, :]).sum()/16
b = (input[0, 1, :, :]+input[1, 1, :, :]+input[2, 1, :, :]+input[3, 1, :, :]).sum()/16
c = (input[0, 2, :, :]+input[1, 2, :, :]+input[2, 2, :, :]+input[3, 2, :, :]).sum()/16
print(‘The mean value of the first channel is %f‘ % a.data)
print(‘The mean value of the first channel is %f‘ % b.data)
print(‘The mean value of the first channel is %f‘ % c.data)
print(‘The output mean value of the BN layer is %f, %f, %f‘ % (m.running_mean.data[0],m.running_mean.data[0],m.running_mean.data[0]))
print(m)
输出结果:
pytorch中nn模块的BatchNorm2d()函数
至于方差以及输出值,大概也是这样进行计算的。