pytorch中的model.eval()和BN层的使用
程序员文章站
2022-03-17 17:28:10
看代码吧~class convnet(nn.module): def __init__(self, num_class=10): super(convnet, self).__in...
看代码吧~
class convnet(nn.module): def __init__(self, num_class=10): super(convnet, self).__init__() self.layer1 = nn.sequential(nn.conv2d(1, 16, kernel_size=5, stride=1, padding=2), nn.batchnorm2d(16), nn.relu(), nn.maxpool2d(kernel_size=2, stride=2)) self.layer2 = nn.sequential(nn.conv2d(16, 32, kernel_size=5, stride=1, padding=2), nn.batchnorm2d(32), nn.relu(), nn.maxpool2d(kernel_size=2, stride=2)) self.fc = nn.linear(7*7*32, num_classes) def forward(self, x): out = self.layer1(x) out = self.layer2(out) print(out.size()) out = out.reshape(out.size(0), -1) out = self.fc(out) return out
# test the model model.eval() # eval mode (batchnorm uses moving mean/variance instead of mini-batch mean/variance) with torch.no_grad(): correct = 0 total = 0 for images, labels in test_loader: images = images.to(device) labels = labels.to(device) outputs = model(images) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum().item()
如果网络模型model中含有bn层,则在预测时应当将模式切换为评估模式,即model.eval()。
评估模拟下bn层的均值和方差应该是整个训练集的均值和方差,即 moving mean/variance。
训练模式下bn层的均值和方差为mini-batch的均值和方差,因此应当特别注意。
补充:pytorch 模型训练模式和eval模型下差别巨大(pytorch train and eval)附解决方案
当pytorch模型写明是eval()时有时表现的结果相对于train(true)差别非常巨大,这种差别经过逐层查看,主要来源于使用了bn,在eval下,使用的bn是一个固定的running rate,而在train下这个running rate会根据输入发生改变。
解决方案是冻住bn
def freeze_bn(m): if isinstance(m, nn.batchnorm2d): m.eval() model.apply(freeze_bn)
这样可以获得稳定输出的结果。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。