简体   繁体   English

将 CUDA 张量转换为 NumPy

[英]Convert CUDA tensor to NumPy

First of all, I tried those solutions: 1 , 2 , 3 , and 4 , but did not work for me.首先,我尝试了这些解决方案: 1234 ,但对我没有用。

After training and testing the neural.network, I am trying to show some examples to verify my work.在训练和测试 neural.network 之后,我试图展示一些例子来验证我的工作。 I named the method predict which I pass the image to it to predict for which class it belongs:我将方法命名为预测,我将图像传递给它以预测它属于哪个 class:

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

Then there is the final step which displays the final result based on the training of the neural.network and done like this:然后是最后一步,显示基于 neural.network 训练的最终结果,如下所示:

# 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()

The error is:错误是:

---------------------------------------------------------------------------
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.

How do I solve this?我该如何解决这个问题?

I tried to change idx to idxs = idxs.cpu().numpy() and the error is:我试图将 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.

Try to change尝试改变

idxs = np.array(idxs)

to

idxs = idxs.cpu().numpy()

And change并改变

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

to

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

So if you're here in 2021 and still have this " TypeError: can't convert CUDA tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first. "因此,如果您在 2021 年来到这里并且仍然遇到“类型错误:无法将 CUDA 张量转换为 numpy。首先使用 Tensor.cpu() 将张量复制到主机内存。

Try x.to("cpu").numpy() from this site https://jbencook.com/pytorch-numpy-conversion/从这个站点尝试x.to("cpu").numpy() https://jbencook.com/pytorch-numpy-conversion/

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

Numpy does not use GPU; Numpy不使用GPU; Numpy operations have to be done in CPU. Numpy 操作必须在 CPU 中完成。 Torch.Tensor can be done in GPU. So wherever numpy operations are there you need to move it to CPU Torch.Tensor 可以在 GPU 中完成。所以无论 numpy 操作在哪里,你都需要将它移动到 CPU

Ex device below is CPU;下面的Ex device是CPU; Model is run in GPU Model 在 GPU 中运行

    df["x"] = df["x"].apply(lambda x: torch.tensor(x).unsqueeze(0))
    df["y"] = df["x"].apply(lambda x: model(x.to(device))[0].detach())

and below when you need to use np.pad, you move it back to cpu在下面当你需要使用 np.pad 时,你将它移回 cpu

df["y"] = df["y"].apply(lambda x: np.pad(x.to("cpu"), [(0, 0), (0,  max_length - x.shape[1])], 'constant')  ) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将 PyTorch CUDA 张量转换为 Z3B7F949B2343F9E5390​​E29F6EF5E1778Z 数组 - Convert PyTorch CUDA tensor to NumPy array cuda 张量的索引列表给出错误 - “无法将 cuda:0 设备类型张量转换为 numpy” - Indexing list of cuda tensors gives error - "can't convert cuda:0 device type tensor to numpy" 无法将 cuda:0 设备类型张量转换为 numpy。 首先使用 Tensor.cpu() 将张量复制到宿主 memory - Can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first TypeError: 无法将 cuda:0 设备类型张量转换为 numpy。 首先使用 Tensor.cpu() 将张量复制到宿主 memory - TypeError: can’t convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first TypeError: 无法将 cuda:0 设备类型张量转换为 numpy。 首先使用 Tensor.cpu() 将张量复制到宿主 memory - TypeError: can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first TypeError:无法将 cuda:0 设备类型张量转换为 numpy。 使用 Tensor.cpu() 先将张量复制到主机内存;&#39; - TypeError: can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first;' TypeError: can't convert cuda:0 device type tensor to numpy. 先用Tensor.cpu()把tensor复制到主机memory。 使用 Pytorch 时出错 - TypeError: can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first. Error occured using Pytorch 将张量转换为 keras 中的 numpy 数组 - Convert a tensor to numpy array in keras 将张量转换为 Tensorflow 中的 numpy 数组? - Convert a tensor to numpy array in Tensorflow? 如何将张量转换为numpy数组 - How to convert tensor to numpy array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM