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()
如果網(wǎng)絡(luò)模型model中含有BN層,則在預(yù)測時應(yīng)當將模式切換為評估模式,即model.eval()。
評估模擬下BN層的均值和方差應(yīng)該是整個訓(xùn)練集的均值和方差,即 moving mean/variance。
訓(xùn)練模式下BN層的均值和方差為mini-batch的均值和方差,因此應(yīng)當特別注意。
補充:Pytorch 模型訓(xùn)練模式和eval模型下差別巨大(Pytorch train and eval)附解決方案
當pytorch模型寫明是eval()時有時表現(xiàn)的結(jié)果相對于train(True)差別非常巨大,這種差別經(jīng)過逐層查看,主要來源于使用了BN,在eval下,使用的BN是一個固定的running rate,而在train下這個running rate會根據(jù)輸入發(fā)生改變。
解決方案是凍住bn
def freeze_bn(m): if isinstance(m, nn.BatchNorm2d): m.eval() model.apply(freeze_bn)
這樣可以獲得穩(wěn)定輸出的結(jié)果。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持本站。
版權(quán)聲明:本站文章來源標注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信