最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
pytorch中model.eval()和BN层使用代码实例
时间:2022-06-25 02:00:02 编辑:袖梨 来源:一聚教程网
本篇文章小编给大家分享一下pytorch中model.eval()和BN层使用代码实例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
代码如下:
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的均值和方差,因此应当特别注意。
相关文章
- 洛克王国世界虫队怎么打 虫队打法教学 11-05
- 洛克王国世界服装积分卡怎么获得 服装积分卡获取攻略 11-05
- 洛克王国世界音速犬在哪 音速犬具体位置 11-05
- 星塔旅人特丽莎值得培养吗 特丽莎角色强度介绍 11-05
- 洛克王国世界蹦蹦果怎么打 蹦蹦果打法教学 11-05
- 二重螺旋妮弗尔夫人怎么配队-妮弗尔夫人阵容搭配推荐 11-05