我们对网络进行了2次训练,每次训练遍历训练数据集。现在来检查模型的训练结果。
我们将使用测试数据集来测试模型。
首先查看一下测试数据集中的内容:
dataiter = iter(testloader)
images, labels = dataiter.next()
# 显示图片
imshow(torchvision.utils.make_grid(images))
print('GroundTruth: ', ' '.join('%5s' % classes[labels[j]] for j in range(4)))
上面图片对应的分类:
GroundTruth: cat ship ship plane
那么,模型对上面的图片是怎么预测的呢:
outputs = net(images)
输出是这10个类的概率值。类的概率值越高,图片属于该类的可能性就越高:
predicted = torch.max(outputs, 1) # 获取最大值所在的类
print('Predicted: ', ' '.join('%5s' % classes[predicted[j]]
for j in range(4)))
输出
Predicted: cat ship ship ship
可以把预测结果跟上面的实际分类比较一下。
让我们看看模型在整个数据测试数据集上的表现:
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('Accuracy of the network on the 10000 test images: %d %%' % (
100 * correct / total))
输出
Accuracy of the network on the 10000 test images: 52 %
可以看到,模型具有一定准确率,在训练中确实学到了一些东西。
按分类看一下模型的预测准确率:
class_correct = list(0. for i in range(10))
class_total = list(0. for i in range(10))
with torch.no_grad():
for data in testloader:
images, labels = data
outputs = net(images)
_, predicted = torch.max(outputs, 1)
c = (predicted == labels).squeeze()
for i in range(4):
label = labels[i]
class_correct[label] += c[i].item()
class_total[label] += 1
for i in range(10):
print('Accuracy of %5s : %2d %%' % (
classes[i], 100 * class_correct[i] / class_total[i]))
输出
Accuracy of plane : 45 %
Accuracy of car : 44 %
Accuracy of bird : 35 %
Accuracy of cat : 27 %
Accuracy of deer : 56 %
Accuracy of dog : 58 %
Accuracy of frog : 70 %
Accuracy of horse : 46 %
Accuracy of ship : 78 %
Accuracy of truck : 57 %