PyTorch-RuntimeError:后端CPU的预期对象,但参数#2“权重”为后端CUDA

时间:2019-05-04 13:41:38

标签: neural-network deep-learning conv-neural-network pytorch torch

我加载了之前训练有素的模型,并希望通过该模型对磁盘中的单个(测试)映像进行分类。我模型中的所有操作都在我的GPU上执行。因此,我通过调用numpy array函数将测试图像的cuda()移至GPU。当我用测试图像的forward()调用模型的numpy array函数时,我得到了RuntimeError: Expected object of backend CPU but got backend CUDA for argument #2 'weight'

这是我用来从磁盘加载图像并调用forward()函数的代码:

test_img = imageio.imread('C:\\Users\\talha\\Desktop\\dog.png')
test_img = imresize(test_img, (28, 28))
test_tensor = torch.from_numpy(test_img)
test_tensor = test_tensor.cuda()
test_tensor = test_tensor.type(torch.FloatTensor)
log_results = model.forward(test_tensor)

软件环境:

火炬:1.0.1

GPU:Nvidia GeForce GTX 1070

操作系统:Windows 10 64-bit

Python:3.7.1

1 个答案:

答案 0 :(得分:0)

在通过GPU发送之前先转换为FloatTensor

因此,操作顺序为:

test_tensor = torch.from_numpy(test_img)

# Convert to FloatTensor first
test_tensor = test_tensor.type(torch.FloatTensor)

# Then call cuda() on test_tensor
test_tensor = test_tensor.cuda()

log_results = model.forward(test_tensor)