1. 程式人生 > >torch報錯TypeError: can't convert CUDA tensor to numpy. Use Tensor.cpu() to copy the tensor

torch報錯TypeError: can't convert CUDA tensor to numpy. Use Tensor.cpu() to copy the tensor

錯誤程式碼:a.numpy()(企圖使用tensor.numpy()函式將torch.Tensor型別轉換成numpy型別)
報錯:TypeError: can’t convert CUDA tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.

原因:如果想把CUDA tensor格式的資料改成numpy時,需要先將其轉換成cpu float-tensor隨後再轉到numpy格式。 numpy不能讀取CUDA tensor 需要將它轉化為 CPU tensor
a.numpy()改為a.cpu().numpy()

即可