numpy 数组可以在 GPU 中运行吗?

我正在使用 PyTorch。我有以下代码:


import numpy as np

import torch


X = np.array([[1, 3, 2, 3], [2, 3, 5, 6], [1, 2, 3, 4]])

X = torch.DoubleTensor(X).cuda()


X_split = np.array_split(X.numpy(), 

                         indices_or_sections = 2, 

                         axis = 0)

X_split

但我收到此错误:


---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-121-870b5d3f67b6> in <module>()

----> 1 X_prime_class_split = np.array_split(X_prime_class.numpy(), 

      2                                      indices_or_sections = 2,

      3                                      axis = 0)

      4 X_prime_class_split


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

错误消息很清楚,我知道如何通过仅包括.cpu(), ie 来修复此错误。X_prime_class.cpu().numpy(). 我只是想知道这是否证实了 numpy 数组不能在 GPU/Cuda 中运行?


尚方宝剑之说
浏览 425回答 1
1回答

至尊宝的传说

不,您通常不能在 GPU 阵列上运行 numpy 函数。PyTorch 为 PyTorch 张量重新实现了 numpy 中的大部分功能。例如,torch.chunk工作方式类似于np.array_split您可以执行以下操作:我正在使用 PyTorch。我有以下代码:import numpy as npimport torchX = np.array([[1, 3, 2, 3], [2, 3, 5, 6], [1, 2, 3, 4]])X = torch.DoubleTensor(X).cuda()X_split = np.array_split(X.numpy(),&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;indices_or_sections = 2,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;axis = 0)X_split但我收到此错误:---------------------------------------------------------------------------TypeError&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Traceback (most recent call last)<ipython-input-121-870b5d3f67b6> in <module>()----> 1 X_prime_class_split = np.array_split(X_prime_class.numpy(),&nbsp;&nbsp; &nbsp; &nbsp; 2&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; indices_or_sections = 2,&nbsp; &nbsp; &nbsp; 3&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; axis = 0)&nbsp; &nbsp; &nbsp; 4 X_prime_class_splitTypeError: can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.错误消息很清楚,我知道如何通过仅包括.cpu(), ie 来修复此错误。X_prime_class.cpu().numpy(). 我只是想知道这是否证实了 numpy 数组不能在 GPU/Cuda 中运行?
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python