for epoch inrange(10): # loop over the dataset multiple times running_loss = 0.0 for i, data inenumerate(trainloader, 0): # get the inputs inputs, labels = data # zero the parameter gradients optimizer.zero_grad() # forward + backward + optimize outputs = net(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step() # print statistics running_loss += loss.item() if i % 2000 == 1999: # print every 2000 mini-batches print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / 2000)) running_loss = 0.0
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))
正常的输出应该为对于测试图片的准确度
1
Accuracy of the network on the 10000 test images: 62 %
这比随机选取(即从10个类中随机选择一个类,正确率是10%)要好很多。看来网络确实学到了一些东西
那么哪些是表现好的类呢?哪些是表现的差的类呢?我们需要输出类的预测结果的准确度,然后进行评估
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
class_correct = list(0.for i inrange(10)) class_total = list(0.for i inrange(10)) with torch.no_grad(): # 不进行跟踪 for data in testloader: # 遍历训练集当中的数据(testloader是训练集) images,labels = data # 获取图像和图像对应的标签 outputs = net(images) # 将图片传给神经网络去识别 _, predicted = torch.max(outputs, 1) # 返回输入张量所有元素的最大值(即得出神经网络的判断结果) c = (predicted == labels).squeeze() # 移除数组中维度为1的维度 for i inrange(4): label = labels[i] # 读取正确的标签 # 返回可遍历的(键, 值) 元组数组,即判断神经网络是否判断正确,并归类至相应的类别 class_correct[label] += c[i].item() class_total[label] += 1# 总样本数量计数+1 for i inrange(10): print('Accuracy of %5s : %2d %%' % (classes[i], 100 * class_correct[i] / class_total[i]))
正常的输出应该是各个标签对应的分类准确度,例如
1 2 3 4 5 6 7 8 9 10
Accuracy of plane : 64 % Accuracy of car : 81 % Accuracy of bird : 50 % Accuracy of cat : 53 % Accuracy of deer : 55 % Accuracy of dog : 52 % Accuracy of frog : 66 % Accuracy of horse : 52 % Accuracy of ship : 76 % Accuracy of truck : 66 %
那么接下来,我们怎么在 GPU 上运行神经网络呢?
在GPU上训练
与将一个张量传递给 GPU 一样,可以这样将神经网络转移到 GPU 上
如果我们有 cuda 可用的话,让我们首先定义第一个设备为可见 cuda 设备:
1 2 3
device = torch.device("cuda:0"if torch.cuda.is_available() else"cpu") # Assuming that we are on a CUDA machine, this should print a CUDA device: print(device)