按照https://www.jianshu.com/p/889dbc684622實現了CIFAR10的分類,
但是轉到GPU上之後,出現error,是數據類型轉換問題。
原在cpu上測試的代碼:
correct = 0
total = 0
for data in testloader:
images, labels = data
outputs = net(Variable(images))
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum()
print('Accuracy of the network on the 10000 test images: %d %%' % (
100 * correct / total))
如果需要在GPU上使用,首先在訓練階段需要將網絡存儲爲GPU上
net.cuda()
然後在測試階段載入,將數據加載到GPU上
inputs, labels = Variable(inputs.cuda()), Variable(target.cuda())
需要注意的是,此時,input已經是Variable,輸入net時不需要再轉成Variable.
另外,predicted是一個tensor類型,不能與variable類型的labels直接比較,需要拿predicted與labels.data比較
最終的測試階段代碼爲:
correct = 0
total = 0
for data in testloader:
images, labels = data
images, labels = Variable(images.cuda()), Variable(labels.cuda())
outputs = net(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels.data).sum()
print('Accuracy of the network on the 10000 test images: %d %%' % (
100 * correct / total))
需要了解Variable類型,
https://blog.csdn.net/qjk19940101/article/details/79555653
tensor是PyTorch中的完美組件,但是構建神經網絡還遠遠不夠,我們需要能夠構建計算圖的tensor,這就是Variable。Variable是對tensor的封裝,操作和tensor是一樣的,但是每個Variable都有三個屬性,Variable中的tensor本身.data,對應tensor的梯度.grad以及這個Variable是通過說明方式得到的.grad_fn