pytorch错误及解决方案

文章目录

不太好做目录,放到代码段里了,每行是一个问题,目前有39个问题。

RuntimeError: CUDA error: device-side assert triggered
RuntimeError:invalid argument 5:k not in range for dimension at /pytorch/ate ... 
ValueError: optimizer got an empty parameter list
The size of tensor a (197) must match the size of tensor b (577) at non-singleton dimension 1
RuntimeError: version_ <= kMaxSupportedFileFormatVersion INTERNAL ASSERT FAILED at /pytorch/caffe2/serialize/inline_container.cc:132, please report a bug to PyTorch. Attempted to read a PyTorch file with version 3, but the maximum supported version for reading is 2. Your PyTorch installation may be too old. (init at /pytorch/caffe2/serialize/inline_container.cc:132)
RuntimeError: Expected to have finished reduction in the prior iteration before starting a new one. This error indicates that your module has parameters that were not used in producing loss. You can enable unused parameter detection by (1) passing the keyword argument `find_unused_parameters=True` to `torch.nn.parallel.DistributedDataParallel`; (2) making sure all `forward` function outputs participate in calculating loss. If you already have done the above two steps, then the distributed data parallel module wasn't able to locate the output tensors in the return value of your module's `forward` function. Please include the loss function and the structure of the return value of `forward` of your module when reporting this issue (e.g. list, dict, iterable).
Setting OMP_NUM_THREADS environment variable for each process to be 1 in def
8.nn.Sequential()如下会出现错误
view size is not compatible with input tensor's size and stride (at least one dimension spans across
semaphore_tracker: There appear to be 11 leaked semaphores to clean up at shutdown
ImportError: libGL.so.1: cannot open shared object file: No such file or directory
RuntimeError: cuda runtime error (11) : invalid argument at /opt/conda/conda-bld/pytorch_1535491974311/work/aten/src/THC/THCGeneral.cpp:663
[PyTorch] IndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1)
/pytorch/aten/src/ATen/native/IndexingUtils.h:20: UserWarning: indexing with dtype torch.uint8 is now deprecated, please use a dtype torch.bool instead.
RuntimeError: zero-dimensional tensor (at position 0) cannot be concatenated
object of type  cannot be safely interpreted as an integer.
RuntimeError: Expected object of scalar type Long but got scalar type Float for argument #2 'target' in call to _thnn_nll_loss_forward
The shape of the mask [32, 8732] at index 0 does not match the shape of the indexed tensor [279424, 1] at index 0
tensorboard ValueError: Duplicate plugins for name projector
RuntimeError: version_ <= kMaxSupportedFileFormatVersion INTERNAL ASSERT FAILED at /pytorch/caffe2/serialize/inline_container.cc:132, please report a bug to PyTorch. Attempted to read a PyTorch file with version 3, but the maximum supported version for reading is 2. Your PyTorch installation may be too old. (init at /pytorch/caffe2/serialize/inline_container.cc:132)
pytorch报错:ValueError: Expected more than 1 value per channel when training, got input size torch.Size([1,512,1,1])
'NoneType' object has no attribute 'parameters' model.parameters()
alueError: loaded state dict contains a parameter group that doesn't match the size of optimizer's group
 is not a checkpoint file
 torch.jit.trace()之正确的模型保存
 RuntimeError: CUDA error: no kernel image is available for execution on the device
 NVIDIA GeForce RTX 3090 with CUDA capability sm_86 is not compatible with the current PyTorch installation.
 site-packages/torch/multiprocessing/spawn.py当中KeyError: 'gpus'
 ZeroDivisionError: division by zero
 graphviz.backend.ExecutableNotFound: failed to execute ['dot', '-Tpng', '-O', 'normal'], make sure
 No such file or directory: 'xdg-open': 'xdg-open'
 tcp://127.0.0.1:FREEPORT
cv2.error: OpenCV(4.6.0) /io/opencv/modules/imgcodecs/src/loadsave.cpp:801: error: (-215:Assertion failed) !_img.empty() in function 'imwrite'
ileNotFoundError: [Errno 2] No such file or directory: '/home/whl/kanghaidong/project/TransferLearning-Tasks/PASCAL_VOC/VOCdevkit/VOC2020/Annotations/.xml'
ValueError: could not convert string to float: '(16)'
PyTorch加载模型model.load_state_dict()问题,Unexpected key(s) in state_dict: “module.features..,Expected .
target.cuda(async=True) SyntaxError: invalid syntax
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 3131: invalid start byte解决办法
OSError: The CUDA lib64 path could not be located in /usr/lib64

前言

提示:介绍了我遇到的一些AI架构的问题,有些解决方案来自于其他博主,没来得及添加引用。


具体内容:见下文。

一、pytorch错误及解决方案

1,RuntimeError: CUDA error: device-side assert triggered

使用pytorch的时候报这个错误说明你label中有些指不在[0, num classes), 区间左闭右开。比如类别数num_class=3, 你的label出现了-1或者3, 4, 5等!!!!

2.RuntimeError:invalid argument 5:k not in range for dimension at /pytorch/ate ... 

训练只有3类,没办法算top5,所以需要修改计算acc时候的topk=(1,3);

3.ValueError: optimizer got an empty parameter list

出现这个问题,很多原因,但是主要原因就是网络定义的不好,有些层没有加进来,或者被改掉了;model.parameters()这个
是看到torch提供的借口里面定义的结构,应该外面也可以,至于加载不进来,和使用了特殊的方法有关,如下:

def get_optimizer(model, args):
    parameters = []
    # for name, param in model.named_parameters():
    #     if 'fc' in name or 'class' in name or 'last_linear' in name or 'ca' in name or 'sa' in name:
    #         parameters.append({'params': param, 'lr': args.base_lr * args.lr_fc_times})
    #     else:
    #         parameters.append({'params': param, 'lr': args.base_lr})
    # parameters = model.parameters()
    if args.optimizer == 'sgd':
        optimizer = torch.optim.SGD(model.parameters(), lr=args.base_lr, momentum=args.momentum, weight_decay=args.weight_decay)
        # return torch.optim.SGD(parameters,
        #                     # model.parameters(),
        #                        args.base_lr,
        #                        momentum=args.momentum, nesterov=args.nesterov,
        #                        weight_decay=args.weight_decay)
对的,正常你定义一个模型,如resnet,是可以使用for name, param in model.named_parameters():
并且,nesterov=args.nesterov这个参数也有问题,即不能够随便乱用。

4.The size of tensor a (197) must match the size of tensor b (577) at non-singleton dimension 1

这个就是维度对不上,一般就是几个错误,数据维度跟网络为度不一致,数据要能够被batch整除,一个就是对dataloader的一个参数drop_last=False; 当然,如果你网络定义有错误,即中间层每层输入,和输出的维度不一致,就是网络在forward操作过程中没对齐,没做好。还是网络问题。

pytorch错误及解决方案_第1张图片

7.Setting OMP_NUM_THREADS environment variable for each process to be 1 in def

OMP_NUM_THREADS 用于控制线程并发数.
 
   测试条件:单个循环请求,持续时间大于15m;
   基础数据:200w
   软件环境:docker; ubuntu 16.04 ;python2.7; faiss:1.4.0-cpu
   检索服务功能: (汉明距离计算 + 欧式距离计算 )

OMP 设置线程的3种方法

设置线程的3种方法
1. 在子语句 data clause 中设置 :
num_threads( )
#pragma omp parallel for default(none) shared(x) private (i) num_threads(3) 
  for(i=0; i<10; i++){
    x[i]=i;
  }


2. 在 run time 函数库中设置 :
omp_set_num_threads( )
omp_set_num_threads(2) 
#pragma omp parallel for default(none) shared(x) private (i) 
  for(i=0; i<10; i++){
    x[i]=i;
  }


3. 在环境变量中设置environment variables
在命令窗口中配置 : export OMP_NUM_THREADS = 3
module load intel  //call intel module
icc -0 -qopenmp myOMP.c -o myOMP.exe  //compile
export OMP_NUM_THREADS=3 ./myOMP.exe   //run

Summary:
1、2、3 优先级依次降低的,也就是前面的设置可以覆盖后面的设置,当然也是相对而言,num_threads子句只会影响当前的并行区域,而omp_set_num_threads对OMP_NUM_THREADS环境变量的覆盖是在整个程序运行期间全局的。   

8.nn.Sequential()如下会出现错误

# self.fc = nn.Sequential(
        #     nn.Linear(int(1024 * block.expansion * s), num_classes),
        #     # nn.Softmax(dim=1))
        # )

self.fc = nn.Linear(int(1024 * block.expansion * s), num_classes)

这两种计算会出现问题,把模块封装到nn.Sequential居然出现了问题,出现计算结果很低的情况,很蛋疼,正常
这个应该是没问题,就是把多个op组到一起。但是测试居然出现问题。
关于softmax还是做到模型的外面的好。而且要区分模型里面一些操作也会用到sofotmax,我们讲的就是fc之后的。

9.view size is not compatible with input tensor's size and stride (at least one dimension spans across

原因:用多卡训练的时候tensor不连续,即tensor分布在不同的内存或显存中。 解决方法:对tensor进行操作时先调用contiguous()。如tensor.contiguous().view()。

10.semaphore_tracker: There appear to be 11 leaked semaphores to clean up at shutdown

最近在跑代码的时候总是会遇到这个错误,明明是UserWarning,但是程序会停止运行,错误提示为
multiprocessing/semaphore_tracker.py:144: UserWarning: semaphore_tracker: There appear to be 4 leaked semaphores to clean up at shutdown
  len(cache))
查了很多资料,这个问题似乎很早之前就有,最早能找到的是在2013年,但是没有什么很好的解决方法,最终发现,需要忽略这个警告就可以了,在运行代码之前加入这一句,希望能帮到大家,我被这个错误耽误了太长时间了
export PYTHONWARNINGS='ignore:semaphore_tracker:UserWarning'

11.ImportError: libGL.so.1: cannot open shared object file: No such file or directory

想要一块小小的GPU做推断和测试都无法满足。。。唯一一块卡还被业务拿走了。。。
强烈建议能够给深度学习工作的小伙伴,配置一块淘汰下来的卡,1080也行啊。。。服务器长期被霸占,还咋个玩,夹缝中求生存。
在新的docker中import的时候出现如下问题:
ImportError: libGL.so.1: cannot open shared object file: No such file or directory

其实就是新容器缺少依赖,安装一下就行了
apt update
apt install libgl1-mesa-glx

12.RuntimeError: cuda runtime error (11) : invalid argument at /opt/conda/conda-bld/pytorch_1535491974311/work/aten/src/THC/THCGeneral.cpp:663

这是一个老问题了。主要原因是pytorch和cuda版本太老,而你用的硬件确实蛋疼的2080ti。
一般是pytorch你用了0.4.1,是基于cuda9.0或者9.2
为什么不能升级,主要是因为DCNv2这种卷积改写了cuda代码,才能够实现梯度计算。这种操作pytorch不支持
自动梯度更新。
但是作者既然已经更新了DCNv2的cuda代码,即支持了pytorch>1.X版本,那么你要升级代码,其他模块最多是
接口或者方法调用上有区别,这些是都可以改的。

解决办法如下:
方法1:
    I have the same issue. RTX2080, for CUDA 10.0 and pytorch 1.0.0. Anyone has solved the same problem please provide the information of the solution. It would help a lot of people. Thanks!
Okay I have solve the problem. You cannot directly install pytorch, instead “pip3 install -U https://download.pytorch.org/whl/cu100/torch-1.0.0-cp36-cp36m-linux_x86_64.whl” work for me.

或者你手动下载,然后用 python3.6 -m pip install https://download.pytorch.org/whl/cu100/torch-1.0.0-cp36-cp36m-linux_x86_64.whl

安装好对应版本的pytorch以后,然后参考如下:
7- cd /CenterNet/src/lib/models/networks
rm -r DCNv2
git clone https://github.com/CharlesShang/DCNv2.git
cd /CenterNet/src/lib/models/networks/DCNv2
python setup.py build develop

即安装新的支持了pytorch>1.X版本。
然后对于BN:
Disable cudnn batch normalization(follow [CenterNet](https://github.com/xingyizhou/pytorch-pose-hg-3d/issues/16)).

    ~~~powershell
   # PYTORCH=/path/to/pytorch # usually ~/anaconda3/envs/MOC/lib/python3.5/site-packages/
   # for pytorch v0.4.1
   sed -i "1254s/torch\.backends\.cudnn\.enabled/False/g" ${PYTORCH}/torch/nn/functional.py
    ~~~
   
    For other pytorch version, you can manually open `torch/nn/functional.py` and find the line with `torch.batch_norm` and replace the `torch.backends.cudnn.enabled` with `False`. 
OK!!!搞定。

按照道理来讲,这个问题就是DCN的问题,那么对于pytorch按照它说的,只要>1.X不死活都行吗,可以验证一下。    
验证结果是,的确是,现在的pytorch版本是1.4.所以网上的答案都是垃圾吧。

13.[PyTorch] IndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1)

import torch
import torch.nn as nn

# a = torch.tensor([[-0.8, -0.2], [-0.2, -0.3], [-0.24, -0.35]]).float()
a = torch.tensor([-0.8, -0.2]).float()
b = torch.tensor([0])
# a = torch.tensor([1, 2, 3])
# b = torch.tensor([1, 0, 1])


print(nn.CrossEntropyLoss()(a, b))

print(nn.CrossEntropyLoss()(a, b))
  File "/Users/kanghaidong/.conda/envs/py36/lib/python3.6/site-packages/torch/nn/modules/module.py", line 727, in _call_impl
    result = self.forward(*input, **kwargs)
  File "/Users/kanghaidong/.conda/envs/py36/lib/python3.6/site-packages/torch/nn/modules/loss.py", line 962, in forward
    ignore_index=self.ignore_index, reduction=self.reduction)
  File "/Users/kanghaidong/.conda/envs/py36/lib/python3.6/site-packages/torch/nn/functional.py", line 2468, in cross_entropy
    return nll_loss(log_softmax(input, 1), target, weight, None, ignore_index, None, reduction)
  File "/Users/kanghaidong/.conda/envs/py36/lib/python3.6/site-packages/torch/nn/functional.py", line 1605, in log_softmax
    ret = input.log_softmax(dim)
IndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1)

Process finished with exit code 1

其实问题很明显,就是这个操作ret = input.log_softmax(dim)不支持batch_size=1的操作。
解决办法就是让batch_size>1.

14./pytorch/aten/src/ATen/native/IndexingUtils.h:20: UserWarning: indexing with dtype torch.uint8 is now deprecated, please use a dtype torch.bool instead.

import warnings
warnings.filterwarnings("ignore", category=UserWarning)

15.RuntimeError: zero-dimensional tensor (at position 0) cannot be concatenated

简单就是转位int,再使用torch.tensor([x]])


torch.cat() 函数传入的tuple里面的tensor维度不可以为0,而我们直接创建一个非list的tensor的时候,就有了zero-dimensional tensor, 这在pytorch0.3 版本没有什么问题,但pytorch0.4版本中,加入了zero-dimensional tensor 的概念,做出了区分。
之所以会这样,是因为我想要做concatenate操作的是一个tensor的浮点型数据,loss.data, 而loss.data 是一个tensor()类型, 跟tensor([])类型是完全不一样的!

16.object of type cannot be safely interpreted as an integer.

错误详情
在使用pycocotools的时候报TypeError: object of type  cannot be safely interpreted as an integer.错误详细信息如下
  File "/home/disk0/zw/workspace/models/research/object_detection/metrics/coco_evaluation.py", line 415, in first_value_func
    self._metrics = self.evaluate()
 
  File "/home/disk0/zw/workspace/models/research/object_detection/metrics/coco_evaluation.py", line 246, in evaluate
    coco_wrapped_groundtruth, coco_wrapped_detections, agnostic_mode=False)
 
  File "/home/disk0/zw/workspace/models/research/object_detection/metrics/coco_tools.py", line 177, in __init__
    cocoeval.COCOeval.__init__(self, groundtruth, detections, iouType=iou_type)
 
  File "/home/zw/anaconda3/envs/competition/lib/python3.6/site-packages/pycocotools/cocoeval.py", line 76, in __init__
    self.params = Params(iouType=iouType) # parameters
 
  File "/home/zw/anaconda3/envs/competition/lib/python3.6/site-packages/pycocotools/cocoeval.py", line 527, in __init__
    self.setDetParams()
 
  File "/home/zw/anaconda3/envs/competition/lib/python3.6/site-packages/pycocotools/cocoeval.py", line 507, in setDetParams
    self.iouThrs = np.linspace(.5, 0.95, np.round((0.95 - .5) / .05) + 1, endpoint=True)
 
  File "<__array_function__ internals>", line 6, in linspace
 
  File "/home/zw/anaconda3/envs/competition/lib/python3.6/site-packages/numpy/core/function_base.py", line 121, in linspace
    .format(type(num)))


解决办法
这个原因应该是numpy更新以后导致的;
1.通过上面的信息可以看到,错误原因是cocoeval.py中的np.linspace函数导致的,发生这个原因是因为np.linspace函数的num参数不支持float类型导致的,找到lib/python3.6/site-packages/pycocotools下的cocoeval.py文件,将507行改成如下
self.iouThrs = np.linspace(.5, 0.95, int(np.round((0.95 - .5) / .05)) + 1, endpoint=True)
原来的是:self.iouThrs = np.linspace(.5, 0.95, np.round((0.95 - .5) / .05) + 1, endpoint=True);具体就是进行int将float强制转换
2.或者安装numpy的1.11.0的版本
如:pip install numpy==1.16

17.RuntimeError: Expected object of scalar type Long but got scalar type Float for argument #2 'target' in call to _thnn_nll_loss_forward

导致这个问题,一般是你重新处理过label;并非由dataloader返回的。比如无监督学习当中你生成了一个label的编码。


在用pytorch的时候,报错RuntimeError: Expected object of scalar type Long but got scalar type Float for argument #2 'target'。研究了一下,发现是关于label的错误。修改办法总结一下:
1、RuntimeError: Expected object of scalar type Long but got scalar type Float for argument #2 'target',在这个报错中,标红的地方是关键,找到程序中的label,比如说在loss处,如下所示:
Loss = torch.nn.CrossEntropyLoss()
loss = Loss(out, label)
修改的时候,直接在label后面加上.long(),如下所示:
Loss = torch.nn.CrossEntropyLoss()
loss = Loss(out, label.long())
2、多次报这个错误后发现,它说是什么类型,直接在label后面加上对应的类型即可。

18.The shape of the mask [32, 8732] at index 0 does not match the shape of the indexed tensor [279424, 1] at index 0

在multibox_loss.py的
98 loss_c[pos] = 0  # filter out pos boxes for now
上一行加上
loss_c = loss_c.view(pos.size()[0], pos.size()[1])
这个是ssd代码已知的问题。可通过上面进行修复。

19.tensorboard ValueError: Duplicate plugins for name projector

解决方案:去torch安装路径的site-packages文件夹下, 删掉tensorboard--2.0.0dist-info 
造成的原因是安装了多个版本,然后冲突了。

20.RuntimeError: version_ <= kMaxSupportedFileFormatVersion INTERNAL ASSERT FAILED at /pytorch/caffe2/serialize/inline_container.cc:132, please report a bug to PyTorch. Attempted to read a PyTorch file with version 3, but the maximum supported version for reading is 2. Your PyTorch installation may be too old. (init at /pytorch/caffe2/serialize/inline_container.cc:132)

解决:
in 1.7:

torch.save(model_.state_dict(), 'model_best_bacc.pth.tar', _use_new_zipfile_serialization=False)
1
then in 1.4:

torch.load('model_best_bacc.pth.tar',map_location='cpu')

21.pytorch报错:ValueError: Expected more than 1 value per channel when training, got input size torch.Size([1,512,1,1])

2.网上查找的原因为模型中用了batchnomolization,训练中用batch训练的时候当前batch恰好只含一个sample,而由于BatchNorm操作需要多于一个数据计算平均值,因此造成该错误。 3.解决方法:在torch.utils.data.DataLoader类中或自己创建的继承于DataLoader的类中设置参数drop_last=True,把不够一个batch_size的数据丢弃。 成功解决。

22.'NoneType' object has no attribute 'parameters' model.parameters()

这个问题是python变量的问题,即model是一个NoneType的类型,这是一个空类型,说明你的model是一个空的,没有在调用的地方进行返回实际的对象。 然后就引发了一系列利用到model的属性出错的问题。 不用怀疑问题是出现在了model没有了paramenters的问题,这个方法是获取model的一个value,通常是一个generate,区别于state_dict是后者是一个dict,还有key的属性,类似的方法有name_paramenters()

23.alueError: loaded state dict contains a parameter group that doesn't match the size of optimizer's group

这个从错误的信息就可以看出来了,是load 模型,希望做resume的时候,或者默认需要做resume的时候,加载的模型参数和
当前的模型参数不一致问题;
往往大部分就是加载错误了不一致的模型结构;

24. is not a checkpoint file

这是一个非常沙雕的错误!
如下:checkpoint='epoch.pth '
然后就爆了上面错误,查了老半天,才发现沙雕的是一个str,呃,恶心了半天,多了一个空格。
checkpoint='epoch.pth';去掉空格就行,因为有些代码在加载模型里面没有对空格做约束。

25.torch.jit.trace()之正确的模型保存

一个复杂model正确trace的艰难之路。

按照提示bug提示来操作
在自己的模型的def forword()上一行加上@torch.jit.script_method,再次保存trace的模型,又会出现新的bug,TypeError: ‘ScriptMethodStub’ object is not callable,这个可能是因为模型中有很多回调的过程,如果模型比较复杂,不适合用这个提示的方法,至于简单的模型,没有尝试过。

问题解决办法
其实这是因为torch.jit.trace()现在是不支持torch.nn.DataParallel,以前好像是支持的,现在不支持了。正确的trace是这样的torch.jit.trace(myModel.module,input_example),完美解决问题。

26.RuntimeError: CUDA error: no kernel image is available for execution on the device

cuda和pytorch的版本不一致。3090的卡算力是8.6
一般清楚下,安装对应的cuda的pytorch版本就行。但是,v100上,即使安装了版本1.6,cuda=10.2的卡,依旧能用。算力问题吗?
升级到torch=1.8或者1.7都行。

27.NVIDIA GeForce RTX 3090 with CUDA capability sm_86 is not compatible with the current PyTorch installation.

这个网上也有很多答案了,大同小异。
大部分人说是pytorch版本太低,大部分都是从1.8开始,我的环境是1.9.0.cuda11.6
但是问题依旧存在,而我1.8.0的环境同样在3090上就没有问题。为什么呢?

3090卡这种性能不行,问题也比较多。对于算力的支持问题就一堆。不像v100这种,很稳定。
这个问题,应该是pytorch版本安装操作问题,即没有按照官网规范操作。自己单独进行pip install pytorch了。没有考虑到cuda的依赖问题。

解决办法很简单,就是去官方找支持cuda11以上的torch安装就行。

28.site-packages/torch/multiprocessing/spawn.py

Traceback (most recent call last):

File "/home/khd/miniconda3/envs/py36/lib/python3.6/site-packages/torch/multiprocessing/spawn.py", line 59, in _wrap

fn(i, *args)

File "/home/khd/kanghaidong/NAS/trivialaugment-master/TrivialAugment/train.py", line 348, in spawn_process

assert worldsize == C.get()['gpus'], f"Did not specify the number of GPUs in Config with which it was started: {worldsize} vs {C.get()['gpus']}"

File "/home/khd/kanghaidong/NAS/trivialaugment-master/theconf-master/theconf/config.py", line 126, in __getitem__

return self.conf[key]

KeyError: 'gpus'

很清楚,问题出现在site-packages/torch/multiprocessing/spawn.py这个程序上了。指定的gpu个数和实际测量的不对应。

修改很清楚,查看gpu的个数和指定gpu的个数是否一致。

但是不建议使用这种方式多gpu的ddp训练,容易忘记导致出错。

29.ZeroDivisionError: division by zero

在除数组成的lst中,最后一个元素为0,当使用到最后一个元素0作为除数时,会提示ZeroDivisionError: division by zero

比如:
int(level * maxval / PARAMETER_MAX)

就要保证PARAMETER_MAX!=0

30.graphviz.backend.ExecutableNotFound: failed to execute ['dot', '-Tpng', '-O', 'normal'], make sure

解决方法:

输入命令import graphviz返回正常,表示python 3.6中已安装graphviz.

根据参考文献1中的提示表明不仅需要在python中成功安装graphviz,还要在系统中安装graphviz,并在系统路径里添加配置(控制面板——》系统——》高级系统设置——》系统属性——》高级——》环境变量——》系统变量——》Path中添加C:\Program Files (x86)\Graphviz2.38\bin;)。

如果是Ubuntu系统,可使用命令 sudo apt-get install graphviz 安装;

如果是Windows系统,则去官网下载安装包,目前稳定版是graphviz-2.38.msi或graphviz-2.38.zip;

如果是Mac系统,可以通过Homebrew安装。

31.No such file or directory: 'xdg-open': 'xdg-open'

yum install xdg-utils

32. tcp://127.0.0.1:FREEPORT

用于pytorch的分布式训练.本质上是pytorch的cpu通信,没有指定端口。比如8080.

33.cv2.error: OpenCV(4.6.0) /io/opencv/modules/imgcodecs/src/loadsave.cpp:801: error: (-215:Assertion failed) !_img.empty() in function 'imwrite'

1.问题描述:已知bbox,裁剪图像并保存
2.代码细节:
...
for bbox_idx, bbox in enumerate(bbox_list):
	img_clip = img[bbox[1]:bbox[3], bbox[0]:bbox[2], :]
	cv2.imwrite('./{}.png'.format(bbox_idx),img_clip)
...
3.报错: 运行成功几张图片后报错
cv2.error: OpenCV(4.6.0) /io/opencv/modules/imgcodecs/src/loadsave.cpp:801: error: (-215:Assertion failed) !_img.empty() in function 'imwrite'

4. 问题分析:
分析:运行几张图片后成功,说明某一张图片,或者某一张图的bbox有问题; 打印出每个bbox数值:
...
#for bbox_idx, bbox in enumerate(bbox_list):
#	img_clip = img[bbox[1]:bbox[3], bbox[0]:bbox[2], :]
	print(bbox)
#	cv2.imwrite('./{}.png'.format(bbox_idx),img_clip)
...
...
[144 248 232 423   2]
[144 247 233 425   2]
[142 251 230 428   2]
[  0 263  56 441   4]
[140 256 228 432   2]
[  0 262  54 442   4]
[  0 259  53 445   4]
[ -3 257  48 446   4] ## 出现负数
...
cv2.error: OpenCV(4.6.0) /io/opencv/modules/imgcodecs/src/loadsave.cpp:801: error: (-215:Assertion failed) !_img.empty() in function 'imwrite'
5. 问题原因:
bbox在检测过程中出了图像边界,导致出现负数,可视化如下图:

pytorch错误及解决方案_第2张图片

将所有小于0的值归零,问题解决:

...
#for bbox_idx, bbox in enumerate(bbox_list):
	bbox[bbox < 0] = 0
#	img_clip = img[bbox[1]:bbox[3], bbox[0]:bbox[2], :]
#	cv2.imwrite('./{}.png'.format(bbox_idx),img_clip)
...
6. 总结:
	这是cv2.imwrite()的问题,首先确保路径正确,其次img注意以下问题:
	1.分割的最小值不能小于0
	2.分割的最大值不能大于图片的宽和高
	3.分割的最大值要大于分割的最小值

在我的检测代码当中,SSD会生成负数框。但是,注意,这个根本不是问题。实际上经过上面的处理,并没有得到解决。

最终是什么问题呢?是一个很沙雕的问题,朋友们可能猜到了,计算机人常常犯的错误,就是文件根本不存在!!!在这里就是图像的路径有问题,导致无法加载图像,就会爆出一个很沙雕的错误。

当然,还有可能是box,label没有parse出来,为什么呢?我的这里错误是加载全部label的时候出错了,使用的还是voc的。这点需要注意。

34.FileNotFoundError: [Errno 2] No such file or directory: '/home/whl/kanghaidong/project/TransferLearning-Tasks/PASCAL_VOC/VOCdevkit/VOC2020/Annotations/.xml'

这个问题是一个很沙雕的问题,在SSD中,对datasets的parse没有做各种空格等等的冗余操作。问题就是一行代码中:
annotation_file = self.root / f"Annotations/{image_id}.xml"
很明显,image_id是空。问题在于加载了空的image_id。即txt中有多余的行。

 pytorch错误及解决方案_第3张图片

35.eval_metrics.py", line 50, in compute_average_precision_per_class

scores.append(float(t[1]))

ValueError: could not convert string to float: '(16)'

pytorch错误及解决方案_第4张图片 

下面是prediction_path = eval_path / f"det_test_{class_name}.txt" 

 

解决上面的问题有三个办法:

  • 1. 对load的模型创建新的字典,去掉不需要的key值"module". 

# original saved file with DataParallelstate_dict = torch.load('checkpoint.pt') # 模型可以保存为pth文件,也可以为pt文件。# create new OrderedDict that does not contain `module.`from collections import OrderedDictnew_state_dict = OrderedDict()for k, v in state_dict.items(): name = k[7:] # remove `module.`,表面从第7个key值字符取到最后一个字符,正好去掉了module. new_state_dict[name] = v #新字典的key值对应的value为一一对应的值。 # load paramsmodel.load_state_dict(new_state_dict) # 从新加载这个模型。 

  • 2. 直接用空白''代替'module.' 
model.load_state_dict({k.replace('module.',''):v for k,v in torch.load('checkpoint.pt').items()}) # 相当于用''代替'module.'。#直接使得需要的键名等于期望的键名。

  • 3.最简单的方法,加载模型之后,接着将模型DataParallel,此时就可以load_state_dict。

如果有多个GPU,将模型并行化,用DataParallel来操作。这个过程会将key值加一个"module. ***"。

model = VGG()# 实例化自己的模型;checkpoint = torch.load('checkpoint.pt', map_location='cpu')  # 加载模型文件,pt, pth 文件都可以;if torch.cuda.device_count() > 1:    # 如果有多个GPU,将模型并行化,用DataParallel来操作。这个过程会将key值加一个"module. ***"。    model = nn.DataParallel(model) model.load_state_dict(checkpoint) # 接着就可以将模型参数load进模型。
  • 4. 总结    从出错显示的问题就可以看出,key值不匹配,因此可以选择多种方法,将模型参数加载进去。 这个方法通常会在load_state_dict过程中遇到。将训练好的一个网络参数,移植到另外一个网络上面,继续训练。或者将训练好的网络checkpoint加载进模型,再次进行训练。可以打印出model state_dict来看出两者的差别。 
    model = VGGNet()params=model.state_dict() #获得模型的原始状态以及参数。for k,v in params.items():    print(k) #只打印key值,不打印具体参数。

 37.target.cuda(async=True) SyntaxError: invalid syntax

改成:

38.UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 3131: invalid start byte解决办法

mac下的问题
删除.DS_Store

 39.OSError: The CUDA lib64 path could not be located in /usr/lib64

 将lib64改为如下:

 

然后进行make,就可以编译成功。我这里用的是nms的cuda和c++代码,需要进行编译。 

 


总结

提示:这里对文章进行总结:

例如:

Enable Ginger Cannot connect to Ginger Check your internet connection
or reload the browserDisable in this text fieldRephraseRephrase current sentence 99+Edit in Ginger×

你可能感兴趣的:(deep,learning,error,programme,pytorch,深度学习,python)