1

我加载了我之前训练的模型,并希望通过这个模型对磁盘中的单个(测试)图像进行分类。我模型中的所有操作都在我的 GPU 上进行。因此,我通过调用函数numpy array将测试图像的移动到 GPU 。cuda()当我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

显卡:Nvidia GeForce GTX 1070

操作系统:Windows 10 64-bit

Python:3.7.1

4

1 回答 1

3

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

因此,操作顺序将是:

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)
于 2019-05-04T14:52:06.533 回答