将CUDA张量转换为NumPy

时间:2019-09-07 09:33:12

标签: python numpy pytorch

首先,我尝试了以下解决方案:1234,但不适用于我。

在训练和测试了神经网络之后,我试图显示一些示例来验证我的工作。我将方法命名为 predict ,将图像传递给该方法以预测其所属的类:

def predict(model, image_path, topk=5):
''' Predict the class (or classes) of an image using a trained deep learning model.
'''

output = process_image(image_path)
output.unsqueeze_(0)
output = output.cuda().float()

model.eval()

with torch.no_grad():
    score = model(output)
    prob, idxs = torch.topk(score, topk)

    # Convert indices to classes
    idxs = np.array(idxs)
    idx_to_class = {val:key for key, val in model.class_to_idx.items()}
    classes = [idx_to_class[idx] for idx in idxs[0]]

    # Map the class name with collected topk classes
    names = []
    for cls in classes:
        names.append(cat_to_name[str(cls)])

    return prob, names

然后是最后一步,它基于神经网络的训练来显示最终结果,并像这样完成:

# TODO: Display an image along with the top 5 classes
x_pos, y_pos = predict(model, img_pil, topk=5)

ax_img = imshow(output)
ax_img.set_title(y_pos[0])

plt.figure(figsize=(4,4))
plt.barh(range(len(y_pos)), np.exp(x_pos[0]))
plt.yticks(range(len(y_pos)), y_pos)

plt.show()

错误是:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-45-e3f9951e9804> in <module>()
----> 1 x_pos, y_pos = predict(model, img_pil, topk=5)
      2
      3 ax_img = imshow(output)
      4 ax_img.set_title(y_pos[0])
      5

1 frames
<ipython-input-44-d77500f31561> in predict(model, image_path, topk)
     14
     15         # Convert indices to classes
---> 16         idxs = np.array(idxs)
     17         idx_to_class = {val:key for key, val in model.class_to_idx.items()}
     18         classes = [idx_to_class[idx] for idx in idxs[0]]

/usr/local/lib/python3.6/dist-packages/torch/tensor.py in __array__(self, dtype)
    456     def __array__(self, dtype=None):
    457         if dtype is None:
--> 458             return self.numpy()
    459         else:
    460             return self.numpy().astype(dtype, copy=False)

TypeError: can't convert CUDA tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.

我该如何解决?

我尝试将idx更改为idxs = idxs.cpu().numpy(),错误是:

TypeError                                 Traceback (most recent call last)
<ipython-input-62-e3f9951e9804> in <module>()
      5
      6 plt.figure(figsize=(4,4))
----> 7 plt.barh(range(len(y_pos)), np.exp(x_pos[0]))
      8 plt.yticks(range(len(y_pos)), y_pos)
      9

/usr/local/lib/python3.6/dist-packages/torch/tensor.py in __array__(self, dtype)
    456     def __array__(self, dtype=None):
    457         if dtype is None:
--> 458             return self.numpy()
    459         else:
    460             return self.numpy().astype(dtype, copy=False)

TypeError: can't convert CUDA tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.

2 个答案:

答案 0 :(得分:2)

尝试更改

idxs = np.array(idxs)

idxs = idxs.cpu().numpy()

然后改变

plt.barh(range(len(y_pos)), np.exp(x_pos[0]))

plt.barh(range(len(y_pos)), np.exp(x_pos[0].cpu().numpy()))

答案 1 :(得分:0)

因此,如果您在 2021 年来到这里并且仍然遇到“TypeError:无法将 CUDA 张量转换为 numpy。首先使用 Tensor.cpu() 将张量复制到主机内存。强>"

从这个网站尝试 x.to("cpu").numpy() https://jbencook.com/pytorch-numpy-conversion/

所以像 idxs = idxs.to("cpu").numpy().squeeze() 这样的东西会起作用。