训练神经网络时报错: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.

训练神经网络时报错: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。下图是修改后的代码。

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

Original: https://www.cnblogs.com/booturbo/p/16341650.html
Author: BooTurbo
Title: 训练神经网络时报错:can’t convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/686090/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球