TypeError: can‘t convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to

一.问题描述

在用GPU训练模型时报如下的错误:

TypeError: can’t convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.


二.原因分析:

GPU上的tensor张量无法转为numpy格式,那我们把它转到CPU上即可。


三.解决方案:

方法非常简单,只需在目标张量后面加 .cpu() 即可。

Before:

loss = valid_loss_function(logits,labels.to(device))

After:

loss = valid_loss_function(logits,labels.to(device)).cpu()

你可能感兴趣的:(numpy,python,深度学习,pytorch)