1.问题描述
在用Pytorch内置的AlexNet网络做分类问题时(数据集有102类),发现损失函数值变化十分缓慢,甚至不下降,只是来回波动。
2.问题分析
用其它模型训练没有出现该问题,说明该问题很大可能是模型本身造成的。
3.解决办法
考虑到AlexNet网络提出较早,没有应用批量归一化技术。为了加快收敛速度,我给每个卷积层后面都加上了BN层。
BN层主要有以下三个作用:
(1)加快网络的训练和收敛的速度
(2)控制梯度爆炸防止梯度消失
(3)防止过拟合
代码如下:
class AlexNet(nn.Module):
def __init__(self):
super(AlexNet, self).__init__()
# input(3,224,224)
self.conv1 = nn.Conv2d(3, 96, kernel_size=11, stride=4)
self.pool1 = nn.MaxPool2d(kernel_size=3, stride=2) self.conv2 = nn.Conv2d(96, 256, kernel_size=5, padding=2) self.pool2 = nn.MaxPool2d(kernel_size=3, stride=2)
self.conv3 = nn.Conv2d(256, 384, kernel_size=3, padding=1)
self.conv4 = nn.Conv2d(384, 384, kernel_size=3, padding=1)
self.conv5 = nn.Conv2d(384, 256, kernel_size=3, padding=1)
self.pool3 = nn.MaxPool2d(kernel_size=3, stride=2) #
self.fc1 = nn.Linear(256 * 5 * 5, 4096)
self.fc2 = nn.Linear(4096, 4096)
self.fc3 = nn.Linear(4096, 102)
def forward(self,x):
batch = x.shape[0]
x=torch.relu(self.conv1(x))
x=self.pool1(x)
nn.BatchNorm2d(96)
x=torch.relu(self.conv2(x))
x=self.pool2(x)
nn.BatchNorm2d(256)
x=self.pool3(torch.relu(self.conv5(self.conv4(self.conv3(x)))))
nn.BatchNorm2d(256)
x=x.view(batch,-1)
x=torch.relu(self.fc1(x))
nn.BatchNorm1d(4096)
x=torch.relu(self.fc2(x))
nn.BatchNorm1d(4096)
x=self.fc3(x)
return x
结果如下:
可以看到训练时损失函数值出现了较为明显的下降,模型可以正常学习!