【问题标题】:TypeError: can’t convert CUDA tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first (fastai)TypeError:无法将 CUDA 张量转换为 numpy。首先使用 Tensor.cpu() 将张量复制到主机内存(fastai)
【发布时间】:2020-07-28 20:41:56
【问题描述】:

我正在关注这里的代码:

https://www.kaggle.com/tanlikesmath/diabetic-retinopathy-with-resnet50-oversampling

但是,在指标计算过程中,我收到以下错误:

File "main.py", line 50, in <module>
 learn.fit_one_cycle(4,max_lr = 2e-3)
...
File "main.py", line 39, in quadratic_kappa
    return torch.tensor(cohen_kappa_score(torch.argmax(y_hat,1), y, weights='quadratic'),device='cuda:0')
...
File "/pfs/work7/workspace/scratch/ul_dco32-conda-0/conda/envs/resnet50/lib/python3.8/site-packages/torch/tensor.py", line 486, in __array__
    return self.numpy()
TypeError: can't convert CUDA tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.

以下是指标和模型:

def quadratic_kappa(y_hat, y):
    return torch.tensor(cohen_kappa_score(torch.argmax(y_hat,1), y, weights='quadratic'),device='cuda:0')

learn = cnn_learner(data, models.resnet50, metrics = [accuracy,quadratic_kappa])
learn.fit_one_cycle(4,max_lr = 2e-3)

正如https://discuss.pytorch.org/t/typeerror-can-t-convert-cuda-tensor-to-numpy-use-tensor-cpu-to-copy-the-tensor-to-host-memory-first/32850/6 讨论中所说,我必须将数据带回cpu。但是我有点迷茫如何做到这一点。

我尝试在所有指标中添加.cpu(),但目前无法解决。

【问题讨论】:

    标签: numpy pytorch cpu


    【解决方案1】:

    我假设yy_hat 都是CUDA 张量,这意味着您需要将它们都带到cohen_kappa_score 的CPU 中,而不仅仅是一个。

    def quadratic_kappa(y_hat, y):
        return torch.tensor(cohen_kappa_score(torch.argmax(y_hat.cpu(),1), y.cpu(), weights='quadratic'),device='cuda:0')
        #                                                        ^^^         ^^^
    

    在 CPU 上已经存在的张量上调用 .cpu() 无效,因此在任何情况下都可以安全使用。

    【讨论】:

      【解决方案2】:

      我从 CPU 版本转到 GPU 版本并收到此错误。这是由于将 metrics=[mean_absolute_error,mean_squared_error] 传递给 Learner 对象(在我的情况下为 tabular_learner)。

      删除 metric 参数暂时为我解决了这个问题。

      【讨论】:

        猜你喜欢
        • 2019-05-22
        • 2021-03-09
        • 2020-09-09
        • 2021-06-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-27
        相关资源
        最近更新 更多