相关文章推荐
深情的路灯  ·  illeegal memory ...·  昨天    · 
年轻有为的签字笔  ·  javascript - Unable ...·  10 月前    · 
温暖的消炎药  ·  十一、springboot ...·  1 年前    · 
重感情的墨镜  ·  解决ASP.NET Web API ...·  1 年前    · 

TypeError: can‘t convert CUDA tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory

项目场景:


运行程序,出现报错信息 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)


改成


aea59c76ec1d4202a27ffd96e6ec627d.png

【报错解决】ERROR: pip‘s dependency resolver does not currently take into account all the packages numpy 报错:”AttributeError: module ‘numpy‘ has no attribute ‘bool‘“ fatal: unable to access ‘https://github xxxxxxxxx的解决方法 MMdetection框架速成系列 第03部分:简述整体构建细节与模块+训练测试模块流程剖析+深入解析代码模块与核心实现 COCO转VOC代码:将coco格式的json文件转换为voc格式的xml文件 【报错解决】ERROR: pip‘s dependency resolver does not currently take into account all the packages numpy 报错:”AttributeError: module ‘numpy‘ has no attribute ‘bool‘“ fatal: unable to access ‘https://github xxxxxxxxx的解决方法 MMdetection框架速成系列 第03部分:简述整体构建细节与模块+训练测试模块流程剖析+深入解析代码模块与核心实现 COCO转VOC代码:将coco格式的json文件转换为voc格式的xml文件
Constrained Output Embeddings for End-to-End Code-Switching Speech Recognition with Only Monolingual Data
RuntimeError: Can‘t call numpy() on Variable that requires grad. Use var.detach().numpy()
出现这个现象的原因是:待转换类型的PyTorch Tensor变量带有梯度,直接将其转换为numpy数据将破坏计算图,因此numpy拒绝进行数据转换,实际上这是对开发者的一种提醒。如果自己在转换数据时不需要保留梯度信息,可以在变量转换之前添加detach()调用。
Pytorch出现RuntimeError: Input type (torch.cuda.FloatTensor) and weight type (torch.FloatTensor)
这个问题的主要原因是输入的数据类型与网络参数的类型不符。
Expected more than 1 value per channel when training, got input size torch.Size
因为模型中用了batchnomolization,训练中用batch训练的时候当前batch恰好只含一个sample,而由于BatchNorm操作需要多于一个数据计算平均值,因此造成该错误。
详细介绍torch中的from torch.utils.data.sampler相关知识
PyTorch中的torch.utils.data.sampler模块提供了一些用于数据采样的类和函数,这些类和函数可以用于控制如何从数据集中选择样本。下面是一些常用的Sampler类和函数的介绍: Sampler基类: Sampler是一个抽象类,它定义了一个__iter__方法,返回一个迭代器,用于生成数据集中的样本索引。 RandomSampler: 随机采样器,它会随机从数据集中选择样本。可以设置随机数种子,以确保每次采样结果相同。 SequentialSampler: 顺序采样器,它会按照数据集中的顺序,依次选择样本。 SubsetRandomSampler: 子集随机采样器
解决 RuntimeError: Tensor for 'out' is on CPU, Tensor for argument #1 'self' is on CPU, but expected them to be on GPU (while checking arguments for addmm)
程序报错:RuntimeError: Tensor for 'out' is on CPU, Tensor for argument #1 'self' is on CPU, but expected them to be on GPU (while checking arguments for addmm) 这个错误提示表明你使用了一个在CPU上的张量与一个在GPU上的张量进行了操作,导致了数据类型不匹配的错误。一种解决方法是将所有的张量都放到同一个设备上进行计算,可以使用 to() 方法来实现:
这将返回一个元组,包含 3 个大小分别为 (6, 2)、(6, 2) 和 (6, 4) 的张量。 需要注意的是,当给定的拆分大小不等于张量在指定维度上的大小时,torch.split() 会引发一个异常。
pytorch报错 RuntimeError: The size of tensor a (25) must match the size of tensor b (50) at non-singleton dimension 1 怎么解决?
这个错误提示表明,在进行某个操作时,张量a和b在第1个非单例维(即除了1以外的维度)上的大小不一致。例如,如果a是一个形状为(5, 5)的张量,而b是一个形状为(5, 10)的张量,则在第二个维度上的大小不匹配。
解决Pytorch中RuntimeError: expected scalar type Double but found Float
解决Pytorch中RuntimeError: expected scalar type Double but found Float
解决AssertionError: size of input tensor and input format are different.tensor shape: (3, 138input_for
解决AssertionError: size of input tensor and input format are different.tensor shape: (3, 138input_for
TensorFlow2._:model.summary() Output Shape为multiple解决方法
TensorFlow2._:model.summary() Output Shape为multiple解决方法
RuntimeError: Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is Fal
RuntimeError: Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is Fal
Tensor to img && imge to tensor (pytorch的tensor转换)
Tensor to img && imge to tensor (pytorch的tensor转换)
pandas中报错:TypeError: reduction operation ‘argmax‘ not allowed for this dtype 的解决办法
pandas中报错:TypeError: reduction operation ‘argmax‘ not allowed for this dtype 的解决办法