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

1、报错:

        一开始程序运行是好的,但是运行中会出现Segmentation fault (core dumped) 了一下有人说把torch改成1.5.1,就手残的改了,之后运行就报如下错:

File "/home/felicty/miniconda3/envs/py3.6/lib/python3.6/site-packages/torch/tensor.py", line 621, 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.

        然后重新安装了虚拟环境,torch==1.8.2同样报错,于是就去查了一下怎么解决,下面是详细解决方法,我的python版本是3.6.1。

2、定位

        找到黄色低纹的文件打开,定位到621行(注意:这个tensor.py的文件位置和报错位置要根据自己的来),找到如下图所示代码

    def __array__(self, dtype=None):
        if has_torch_function_unary(self):
            return handle_torch_function(Tensor.__array__, (self,), self, dtype=dtype)
        if dtype is None:
            return self.numpy()
        else:
            return self.numpy().astype(dtype, copy=False)

3、更改

        将上述代码更改为如下:

    def __array__(self, dtype=None):
        if has_torch_function_unary(self):
            return handle_torch_function(Tensor.__array__, (self,), self, dtype=dtype)
        
        if self.device.type == 'cuda':
            # 如果张量在 CUDA 设备上,先将其转移到 CPU,然后再转换为 NumPy 数组
            return self.cpu().numpy()
        else:
            if dtype is None:
                return self.numpy()
            else:
                return self.numpy().astype(dtype, copy=False)

        注意:这个更改是直接改的torch源包里的代码,不放心怕改错的,可以把原代码注销,如下图:

4、再次运行

        改完之后再运行,就不报错了

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值