首先来看看不做批量归一化有什么问题:
如图所示:如果我们在激活之前不做归一化的话,值有可能会很大或者很小,就没梯度了,导致梯度弥散,而做了批量归一化以后就可以将数值控制在0~1或者-1~1之间,只是将数据压缩了,但没有改变原始数据的信息,这是就一直有梯度,可以进行梯度的更新。
归一化的作用:减少特征之间的差异度,把数据压缩到非饱和区域,因为梯度太小不利于学习,所以压缩到-1到1之间。
批量归一化:可以加速学习和收敛,稳定训练,将每一层的输入变换到均值0和单位标准差的地方,是非常重要的加速收敛和缓解过拟合的手段。
最大值归一化:适用于有界范围内的数据,比如图像最大就255,是有边界的。
均值归一化:用于无边界的数据。
一般还需要先归一化再去均值。
import numpy as np
import matplotlib.pyplot as plt
#最值归一化的两种方式
def Normalization1(x):
'''归一化(0~1)'''
'''x_=(x−x_min)/(x_max−x_min)'''
return [(float(i)-min(x))/float(max(x)-min(x)) for i in x]
def Normalization2(x):
'''归一化(-1~1)'''
'''x_=(x−x_mean)/(x_max−x_min)'''
return [(float(i)-np.mean(x))/(max(x)-min(x)) for i in x]
#均值方差归一化
def z_score(x):
'''标准化(μ=0,σ=1)'''
'''x∗=(x−μ)/σ'''
x_mean=np.mean(x)
s2=sum([(i-np.mean(x))*(i-np.mean(x)) for i in x])/len(x)
return [(i-x_mean)/s2 for i in x]
l=[-10, 5, 5, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 15, 15, 30]
l1=[]
# for i in l:
# i+=2
# l1.append(i)
# print(l1)
cs=[]
for i in l:
c=l.count(i)
cs.append(c)
print(cs)
n=Normalization2(l)
z=z_score(l)
print(n)
print(z)
plt.plot(l,cs)
plt.plot(z,cs)
plt.show()
例如对于一批输入的图片,x = x/127.5-1或者Img = (Img/255-0.5)*2