【问题标题】:Can numpy arrays run in GPUs?numpy 数组可以在 GPU 中运行吗?
【发布时间】:2020-11-03 08:10:35
【问题描述】:

我正在使用 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() 来修复此错误,即。 X_prime_class.cpu().numpy()。我只是想知道这是否证实 numpy 数组不能在 GPU/Cuda 中运行?

【问题讨论】:

    标签: python numpy pytorch gpu


    【解决方案1】:

    不,您通常不能在 GPU 阵列上运行 numpy 函数。 PyTorch 为 PyTorch 张量重新实现了 numpy 中的大部分功能。例如,torch.chunk 的工作方式与 np.array_split 类似,因此您可以执行以下操作:

    X = np.array([[1, 3, 2, 3], [2, 3, 5, 6], [1, 2, 3, 4]])
    X = torch.DoubleTensor(X).cuda()
    X_split = torch.chunk(X, chunks=2, dim=0)
    

    X 拆分为多个张量,而无需将X 移出GPU。

    【讨论】:

      猜你喜欢
      • 2021-05-04
      • 2020-08-10
      • 1970-01-01
      • 2018-01-21
      • 2015-07-16
      • 1970-01-01
      • 2021-11-04
      • 1970-01-01
      • 2018-10-24
      相关资源
      最近更新 更多