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、再次运行
改完之后再运行,就不报错了