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

在使用Pytorch训练模型时遇到TypeError,原因是尝试将CUDA tensor直接转换为numpy数组。解决方法是先将CUDA tensor通过`.cpu()`迁移到CPU,然后再调用`.numpy()`进行转换。此问题在Python 3.7环境中出现,但在Python 3.8环境中未复现,可能与Python版本有关。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述

在训练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

评论 56
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值