类型错误:can’;t将CUDA张量转换为numpy。首先使用Tensor.cpu()将Tensor复制到主机内存(fastai)
我在这里遵循代码: 但是,在度量计算过程中,我得到以下错误:类型错误:can’;t将CUDA张量转换为numpy。首先使用Tensor.cpu()将Tensor复制到主机内存(fastai),numpy,pytorch,cpu,Numpy,Pytorch,Cpu,我在这里遵循代码: 但是,在度量计算过程中,我得到以下错误: 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'),
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.
正如讨论中所说的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()
,但到目前为止无法解决它。我假设y
和y\u hat
都是CUDA张量,这意味着您需要将它们都带到cpu进行cohen\u kappa\u得分
,而不仅仅是一个
def quadratic_kappa(y_hat,y):
返回torch.tensor(cohen_kappa_分数(torch.argmax(y_hat.cpu(),1),y.cpu(),weights='quadratic'),device='cuda:0')
# ^^^ ^^^
对已经在cpu上的张量调用.cpu()
,没有效果,因此在任何情况下都可以安全使用
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)