defforward(self, x): x = self.pool(F.relu(self.conv1(x))) x = self.pool(F.relu(self.conv2(x))) x = x.view(-1, 16 * 5 * 5) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return x
correct = 0 total = 0 with torch.no_grad(): for data in testloader: images, labels = data outputs = net(images) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum().item()
print(f'Accuracy of the network on the 10000 test images: {100 * correct / total:.2f}%')
6.2 各类别的准确率
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# 获取所有类别的准确率 class_correct = list(0.for i inrange(10)) class_total = list(0.for i inrange(10))
with torch.no_grad(): for data in testloader: images, labels = data outputs = net(images) _, predicted = torch.max(outputs.data, 1) c = (predicted == labels).squeeze() for i inrange(4): # batch_size label = labels[i] class_correct[label] += c[i].item() class_total[label] += 1
for i inrange(10): print(f'Accuracy of {classes[i]:5s} : {100 * class_correct[i] / class_total[i]:2.2f} %')