批量规范化
- 1、为啥要批量规范化呢?
- 2、如何批量规范化呢?
- 3、实现批量归一化。
- 4、定义BatchNorm层:
- 5、定义神经网络:
- 6、开始训练:
1、为啥要批量规范化呢?
1、可持续加速深层网络的收敛速度。
2、对于深层网络来说非常复杂,容易导致过拟合。
2、如何批量规范化呢?
均值u = (∑x)/B B是样本个数
方差o^2 = (∑(x - u)^2)/B + c (c是小噪声) 为啥要设置这个c呢,避免分母除0
BN = gamma * (x - u)/o + beta
3、实现批量归一化。
代码如下:
# moving_mean :均值, moving_var 方差, eps:就是上边那个 c(小噪声),避免太小。 momentum : 用于更新moving_mean 和moving_var
def batch_norm(X, gamma, beta, moving_mean, moving_var, eps, momentum):#用于检测当前是训练模式还是预测模式if not torch.is_grad_enabled():#如果是在训练模式下,直接使用传入的移动平均所得到的均值和方差X_hat = (X - moving_mean) / torch.sqrt(moving_var + eps)else:# X.shape表示呢,X这个张量的形状维度大小。#例如:全连接层:(样本数,输入特征) 而,卷积层:(批量大小,输出通道,高度,宽度)assert len(X.shape) in (2,4)if len(X.shape) == 2:#使用全连接层的情况,计算特征维上的均值和方差。mean = X.mean(dim=0) #按列来计算特征值的均值var = ((X - mean) **2 ).mean(dim=0) #均值方差else:#对于卷积层来说,(批量大小,通道,高度,宽度)# 理解一下这里的(dim=(0,2,3)),对于上边的dim =0,相当于压缩列方向。# 那么看dim =(0,2,3),相当于压缩,批量方向,高度方向,宽度方向,最终会只剩下通道方向,所以结果是:1*n,1*1mean = X.mean(dim=(0,2,3),keepdim =True)var = ((X - mean) ** 2).mean(dim=(0, 2, 3), keepdim=True)X_hat = (X - mean) / torch.sqrt(var + eps)# 更新移动平均的均值和方差moving_mean = momentum * moving_mean + (1.0 - momentum) * meanmoving_var = momentum * moving_var + (1.0 - momentum) * varY = gamma * X_hat + betareturn Y,moving_mean.data,moving_var.data
4、定义BatchNorm层:
class BatchNorm(nn.Module):# num_features:完全连接层的输出数量或卷积层的输出通道数。# num_dims:2表示完全连接层,4表示卷积层def __init__(self, num_features, num_dims):super().__init__()if num_dims == 2:# 全连接层shape = (1, num_features)else:# 卷积层,高度和宽度都设置为1 ,是为了使用广播机制。shape = (1, num_features, 1, 1)# 参与求梯度和迭代的拉伸和偏移参数,分别初始化成1和0self.gamma = nn.Parameter(torch.ones(shape))self.beta = nn.Parameter(torch.zeros(shape))# 非模型参数的变量初始化为0和1self.moving_mean = torch.zeros(shape)self.moving_var = torch.ones(shape)def forward(self, X):# 如果X不在内存上,将moving_mean和moving_var# 复制到X所在显存上if self.moving_mean.device != X.device:self.moving_mean = self.moving_mean.to(X.device)self.moving_var = self.moving_var.to(X.device)# 保存更新过的moving_mean和moving_varY, self.moving_mean, self.moving_var = batch_norm(X, self.gamma, self.beta, self.moving_mean,self.moving_var, eps=1e-5, momentum=0.9)return Y
5、定义神经网络:
net = nn.Sequential(nn.Conv2d(1, 6, kernel_size=5), BatchNorm(6, num_dims=4), nn.Sigmoid(),nn.AvgPool2d(kernel_size=2, stride=2),nn.Conv2d(6, 16, kernel_size=5), BatchNorm(16, num_dims=4), nn.Sigmoid(),nn.AvgPool2d(kernel_size=2, stride=2), nn.Flatten(),nn.Linear(16*4*4, 120), BatchNorm(120, num_dims=2), nn.Sigmoid(),nn.Linear(120, 84), BatchNorm(84, num_dims=2), nn.Sigmoid(),nn.Linear(84, 10))
6、开始训练:
lr, num_epochs, batch_size = 1.0, 10, 256
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)
d2l.train_ch6(net, train_iter, test_iter, num_epochs, lr, d2l.try_gpu())