深度学习常见问题汇总

1. Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu!

原因

参与运算的两个或多个变量,有的在CPU上,有的在GPU上

解决

首先找到报错的行,看看计算时都用到哪些变量或者数据,使用.is_cuda这个属性去查看到底哪些是在GPU上,然后统一放在一个设备上

print("validity_label is "+str(validity_label.is_cuda))
# 将validity_label放在cuda上
validity_label = validity_label.cuda()
print("validity_label is " + str(validity_label.is_cuda))

2.Tensor for argument #2 ‘mat1’ is on CPU, but expected it to be on GPU (while checking arguments for addmm)

原因

为了使模型在GPU上进行计算,需要将变量和模型都增加.to(device),都搬到GPU上去即可

解决

与错误1一样,将变量和模型搬到GPU上

3.can't convert cuda:0 device type 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

解决

number = dataList[dataList_size - 2].detach().numpy()

变为

number = dataList[dataList_size - 2].detach().cpu().numpy()

4.UserWarning: Creating a tensor from a list of numpy.ndarrays is extremely slow.

原因

如果list中没有ndarrays,则选择list->tensor更快。

如果list中有ndarrays,则选择list->ndarrays->tensor更快;

解决

z = Variable(Tensor(z))

变为

z = Variable(Tensor(np.array(z)))

5.TypeError: can't convert CUDA tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.

原因

numpy不能读取CUDA tensor 需要将它转化为 CPU tensor

如果想把CUDA tensor格式的数据改成numpy时,需要先将其转换成cpu float-tensor随后再转到numpy格式

解决

number = dataList[dataList_size - 2].detach().numpy()

变为

number = dataList[dataList_size - 2].detach().cpu().numpy()
posted @ 2022-12-19 00:24  Frodo1124  阅读(232)  评论(0编辑  收藏  举报