pytorch deeplearning测试阶段GPU测试问题

按照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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值