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

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

我在这里遵循代码:

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(),但到目前为止无法解决。

我假设 yy_hat 都是 CUDA 张量,这意味着您需要将它们都带到 CPU 以获得 cohen_kappa_score,不止一个

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() 没有任何效果,因此在任何情况下都可以安全使用。

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

删除度量参数暂时解决了我的问题。