训练神经网络时报错:can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.

 

 

在跑网络的时候,报错TypeError:can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host_memory first.

错误在于:train_loss.append(loss.data) 和 valid_loss.append(loss.data)这两行代码,将loss.data改为loss.data.cpu(),也就是将CUDA数据转化为CPU数据,

因为train_loss = np.mean(train_loss) 及 valid_loss = np.mean(valid_loss) 这两行试图将GPU中的CUDA tensor 转化为numpy,但是numpy不能处理CUDA tensor,要先将GPU中的tensor复制到CPU内存中,再传给numpy。下图是修改后的代码。

 

posted @ 2022-06-04 12:55  BooTurbo  阅读(19115)  评论(0编辑  收藏  举报