完整报错:TypeError: can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.
环境:python3,笔记本带cuda
原因:numpy只能再cpu上调用,GPU上的tensor不可调用(如何将model,tensor放到GPU上可以参考我的另一篇博客:pytorch将model放置到GPU(cuda)上,运行时报错Expected all tensors to be on the same device, but found at least tw_Wsyoneself的博客-CSDN博客)
报错代码:
loss_value = np.mean(loss.detach().numpy())
accracy = np.mean((torch.argmax(out, 1) == torch.argmax(y, 1)).numpy())
尝试解决:
方法一:降低numpy的版本:听说有效,亲测无效(可能是我的环境问题),如果无效可以尝试方法二
pip install --user numpy==1.19
方法二:在调用numpy前转为cpu,修改后的代码:
loss_value = np.mean(loss.cpu().detach().numpy())
accracy = np.mean((torch.argmax(out, 1) == torch.argmax(y, 1)).cpu().numpy())
成功运行~