项目场景:
运行程序,出现报错信息 TypeError: can't convert CUDA tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.。
Traceback (most recent call last): File "tools/demo.py", line 97, in <module> visualize_result(gallery_img, detections, similarities) File "tools/demo.py", line 41, in visualize_result (x1, y1), x2 - x1, y2 - y1, fill=False, edgecolor="#4CAF50", linewidth=3.5 File "/environment/miniconda3/lib/python3.7/site-packages/matplotlib/axes/_base.py", line 2358, in add_patch self._update_patch_limits(p) File "/environment/miniconda3/lib/python3.7/site-packages/matplotlib/axes/_base.py", line 2381, in _update_patch_limits patch_trf = patch.get_transform() File "/environment/miniconda3/lib/python3.7/site-packages/matplotlib/patches.py", line 278, in get_transform return self.get_patch_transform() + artist.Artist.get_transform(self) File "/environment/miniconda3/lib/python3.7/site-packages/matplotlib/patches.py", line 752, in get_patch_transform bbox = self.get_bbox() File "/environment/miniconda3/lib/python3.7/site-packages/matplotlib/patches.py", line 845, in get_bbox return transforms.Bbox.from_extents(x0, y0, x1, y1) File "/environment/miniconda3/lib/python3.7/site-packages/matplotlib/transforms.py", line 839, in from_extents bbox = Bbox(np.reshape(args, (2, 2))) File "<__array_function__ internals>", line 6, in reshape File "/home/featurize/work/.local/lib/python3.7/site-packages/numpy/core/fromnumeric.py", line 298, in reshape return _wrapfunc(a, 'reshape', newshape, order=order) File "/home/featurize/work/.local/lib/python3.7/site-packages/numpy/core/fromnumeric.py", line 54, in _wrapfunc return _wrapit(obj, method, *args, **kwds) File "/home/featurize/work/.local/lib/python3.7/site-packages/numpy/core/fromnumeric.py", line 43, in _wrapit result = getattr(asarray(obj), method)(*args, **kwds) File "/home/featurize/work/.local/lib/python3.7/site-packages/torch/tensor.py", line 458, in __array__ return self.numpy() TypeError: can't convert CUDA tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.
问题描述
这个问题是由 python 3.7 版本引起的。修改部分 python 源码即可。
根据报错信息,定位到 /home/featurize/work/.local/lib/python3.7/site-packages/torch/tensor.py
解决方案:
将 self.numpy() 改成 self.cpu().numpy(),即找到 tensor.py 的第 458 行
def __array__(self, dtype=None): if dtype is None: return self.numpy() else: return self.numpy().astype(dtype, copy=False)
改成