问题描述
在训练Pytorch模型的时候,报错
Traceback (most recent call last):
File "train.py", line 469, in <module>
train(hyp, tb_writer, opt, device)
File "train.py", line 347, in train
save_dir=log_dir)
File "/home/xxx/Detection/test.py", line 176, in test
plot_images(img, output_to_target(output, width, height), paths, str(f), names) # predictions
File "/home/xxx/Detection/utils/utils.py", line 914, in output_to_target
return np.array(targets)
File "/home/xxx/anaconda3/envs/pytorch1.5/lib/python3.7/site-packages/torch/tensor.py", line 492, in __array__
return self.numpy()
TypeError: 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
解决方法
将报错代码self.numpy()改为self.cp