算法过程:
-
假设batchsize=8,channels=6,feature map=5×5
-
对于同一个batchsize的同一个通道,求出该通道的均值与方差,根据假设求出了6个通道的均值x与方差N。
-
在每一个通道上,feature map上的值进行如下运算:
其中 E【X】表示均值,x表示 feature map 上面的值, Var【x】表示方差N,另外两个参数是要学习的,y表示输出的结果,可以看出前后运算结果的维度不变。依然是8×6×5×5,
pytorch代码实现:
import torch
from torch import nn
m = nn.BatchNorm2d(3) # 3 == number of 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.0
b = (input[0, 1, :, :]+input[1, 1, :, : ]+ input[2, 1, :, :]+input[3, 1, :, :]).sum()/16.0
c = (input[0, 2, :, :]+input[1, 2, :, : ]+ input[2, 2, :, :]+input[3, 2, :, :]).sum()/16.0
print('the mean value of the channels is %f, %f, %f'%(a.data, b.data, c.data))
print('the output mean value of the BN layer is %f, %f, %f'%(m.running_mean.data[0],m.running_mean.data[1],m.running_mean.data[2]))
print(m)
结果:
the mean value of the channels is 0.228274, 0.131121, 0.049071
the output mean value of the BN layer is 0.022827, 0.013112, 0.004907
BatchNorm2d(3, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
可以看出结果区别不大。
算法目的: