def test_se(Model, weights, use_model_num, test_loader):
index = len(weights) - use_model_num
weights = weights[index:]
model_list = [Model() for _ in weights]
for model, weight in zip(model_list, weights):
model.load_state_dict(weight)
model.eval()
if cuda:
model.cuda()
test_loss = 0
correct = 0
for data, target in test_loader:
if cuda:
data, target = data.cuda(), target.cuda()
data, target = Variable(data), Variable(target)
output_list = [model(data).unsqueeze(0) for model in model_list]
output = torch.mean(torch.cat(output_list), 0).squeeze()
test_loss += F.nll_loss(output, target).data[0]
pred = output.data.max(1)[1]
correct += pred.eq(target.data).cpu().sum()
test_loss /= len(test_loader)
print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
test_loss, correct, len(test_loader.dataset),
100 * correct / len(test_loader.dataset)))
return test_loss
评论列表
文章目录