解决“TypeError: can‘t convert cuda:0 device type tensor to numpy. ......”问题

问题描述

在训练Pytorch模型的时候,报错

Traceback (most recent call last):
  File "train.py", line 469, in 
    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.cpu().numpy()即可

补充说明

之前报错的代码是在101服务器上,创建的虚拟环境中Python=3.7,在跑实验的时候出现报错;今天在100服务器上跑同样的实验没有报错,经查在100服务器上创建的虚拟环境中Python=3.8;目测是Python版本的缘故,看来还是python3.8好用一些

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