YOLOv5下载编译运行-口罩检测

目录

一、YOLOv5程序下载

        1. yolov5程序下载

        2.口罩数据集下载 

二、编译运行代码 

        1.使用pycharm打开上面的文件夹 

        2.pycharm训练参数配置 

        3.编译运行

三、使用训练好的模型进行预测

        1. 预测环境配置 

四、训练和预测过程遇到的错误及解决办法

        1. 训练遇到的报错 

        2. 预测编译遇到的错误及解决办法 

        3. 一些其它错误的解决办法 

        4. YOLOv5训练不显示GFLOPs问题



一、YOLOv5程序下载

        1. yolov5程序下载

GitHub - ultralytics/yolov5: YOLOv5 🚀 in PyTorch > ONNX > CoreML > TFLite

      依赖包安装 

     在命令行下进入yolov5目录,执行下面的命令,会把依赖包安装

pip install -r requirements.txt  # install

而我的环境有的依赖包已经安装过,不执行,编译遇到缺少什么,就安装什么 

        2.口罩数据集下载 

 链接:https://pan.baidu.com/s/1RP3wXuQnGsO87JqgK_bK3g 
提取码:j236 
--来自百度网盘超级会员V1的分享 

解压后文件夹如下,标出来的就是数据集,解压下来的yolov5代码是旧版的,不用,只要数据集。 

将上面两步得到的代码和数据集放到同一个目录 

二、编译运行代码 

        1.使用pycharm打开上面的文件夹 

        2.pycharm训练参数配置 

 

上图第2步的参数设置如下

--data
D:/deep_learn/yolov5_20230418/MaskDataSet/data.yaml
--weights
''
--cfg
D:/deep_learn/yolov5_20230418/yolov5-master/models/yolov5s.yaml

 --data   数据集指定, --weights 预训练权重,用单引号‘ ’代码不使用迁移学习,从0开始训练 

-- cfg    模型配置文件,其它参数不设置就使用默认的。

  下图是官方的训练参数配置

 注意--workers 的default值需要修改为0,否则编译报错。

 

关于编译遇到的报错,在最后有说明 

        3.编译运行

         编译结束后log信息如下,训练好的模型保存在Results saved to runs\train\exp2

   100 epochs completed in 0.167 hours.
Optimizer stripped from runs\train\exp2\weights\last.pt, 14.5MB
Optimizer stripped from runs\train\exp2\weights\best.pt, 14.5MB

Validating runs\train\exp2\weights\best.pt...
Fusing layers... 
YOLOv5s summary: 157 layers, 7015519 parameters, 0 gradients
                 Class     Images  Instances          P          R      mAP50   mAP50-95: 100%|██████████| 1/1 [00:00<00:00,  1.79it/s]
                   all         29        162      0.878      0.349      0.439      0.211
                  mask         29        142      0.755      0.697       0.72      0.342
               no-mask         29         20          1          0      0.159     0.0807
Results saved to runs\train\exp2

三、使用训练好的模型进行预测

        1. 预测环境配置 

 

参数详细设置

--weights
D:/deep_learn/yolov5_20230418/yolov5-master/runs/train/exp2/weights/best.pt
--source
D:/deep_learn/yolov5_20230418/yolov5-master/data/images

 预测时指定使用训练好的模型路径和待预测的图像数据

   待预测的图像如下 

预测结果如下

四、训练和预测过程遇到的错误及解决办法

        1. 训练遇到的报错 

使用train.py报错使用
1.
requirements: YOLOv5 requirement "gitpython" not found, attempting AutoUpdate...
requirements:  AutoUpdate skipped (offline)
Traceback (most recent call last):
  File "D:\deep_learn\yolov5_20230418\yolov5-master\train.py", line 67, in <module>
    GIT_INFO = check_git_info()
  File "D:\SoftInstall\Anaconda\envs\openmmlab\lib\contextlib.py", line 75, in inner
    return func(*args, **kwds)
  File "D:\deep_learn\yolov5_20230418\yolov5-master\utils\general.py", line 359, in check_git_info
    import git
ModuleNotFoundError: No module named 'git'
解决办法:pip install gitpython

2. 
  Traceback (most recent call last):
  File "D:\SoftInstall\Anaconda\envs\openmmlab\lib\site-packages\git\__init__.py", line 89, in <module>
    refresh()
  File "D:\SoftInstall\Anaconda\envs\openmmlab\lib\site-packages\git\__init__.py", line 76, in refresh
    if not Git.refresh(path=path):
  File "D:\SoftInstall\Anaconda\envs\openmmlab\lib\site-packages\git\cmd.py", line 392, in refresh
    raise ImportError(err)
ImportError: Bad git executable.
解决办法:按照报错所在文件,在执行git代码前面添加下方代码
  os.environ['GIT_PYTHON_REFRESH'] = 'quiet'
例子:
如:os.environ['GIT_PYTHON_REFRESH'] = 'quiet'  #添加代码
    if not Git.refresh(path=path):
        return
		
3.
  File "D:\SoftInstall\Anaconda\envs\openmmlab\lib\site-packages\torch\__init__.py", line 129, in <module>
    raise err
OSError: [WinError 1455] 页面文件太小,无法完成操作。 Error loading "D:\SoftInstall\Anaconda\envs\openmmlab\lib\site-packages\torch\lib\cufft64_10.dll" or one of its dependencies.
解决办法
   修改train.py中配置项workers的默认值,从初始值8修改为0(也可以试试1或2等较小的数)。

        2. 预测编译遇到的错误及解决办法 

使用detect.py报错
1.
  File "D:\deep_learn\yolov5_20230418\yolov5-master\utils\dataloaders.py", line 22, in <module>
    import psutil
ModuleNotFoundError: No module named 'psutil'
解决办法:
pip install psutil

2.
  File "D:\deep_learn\yolov5_20230418\yolov5-master\utils\plots.py", line 18, in <module>
    import seaborn as sn
ModuleNotFoundError: No module named 'seaborn'
解决办法:
pip install seaborn

 这就是缺少什么就安装什么

        3. 一些其它错误的解决办法 

编译报错
File "D:\SoftInstall\Anaconda\envs\openmmlab\lib\site-packages\torch\nn\modules\activation.py", line 472, in forward
    return F.hardswish(input, self.inplace)
  File "D:\SoftInstall\Anaconda\envs\openmmlab\lib\site-packages\torch\nn\modules\module.py", line 1207, in __getattr__
    raise AttributeError("'{}' object has no attribute '{}'".format(
AttributeError: 'Hardswish' object has no attribute 'inplace'

修改代码
    def forward(self, input: Tensor) -> Tensor:
#        return F.hardswish(input, self.inplace)   #原来的代码
         return F.hardswish(input)                 #修改后的代码


训练报错

File "D:\BaiduNetdiskDownload\YOLO5\yolov5-master\models\yolo.py", line 150, in _initialize_biases
    b[:, 4] += math.log(8 / (640 / s) ** 2)  # obj (8 objects per 640 image)
RuntimeError: a view of a leaf Variable that requires grad is being used in an in-place operation.

修改
  for mi, s in zip(m.m, m.stride):  # from
            b = mi.bias.view(m.na, -1)  # conv.bias(255) to (3,85)
            with torch.no_grad():  #报错,增加这个代码
                 b[:, 4] += math.log(8 / (640 / s) ** 2)  # obj (8 objects per 640 image) #缩进
                 b[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) #缩进  # cls
            mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)

报错
 File "D:\SoftInstall\Anaconda\envs\openmmlab\lib\site-packages\numpy\__init__.py", line 305, in __getattr__
    raise AttributeError(__former_attrs__[attr])
AttributeError: module 'numpy' has no attribute 'int'.

原因:numpy.int在NumPy 1.20中已弃用,在NumPy 1.24中已删除。

解决方式:将numpy.int更改为numpy.int_,int。

方法:点击出现错误代码链接会自动跳转到相应numpy.int的位置

File "D:\BaiduNetdiskDownload\YOLO5\yolov5-master\utils\datasets.py", line 406, in __init__
    self.batch_shapes = np.ceil(np.array(shapes) * img_size / stride + pad).astype(np.int) * stride
  File "D:\SoftInstall\Anaconda\envs\openmmlab\lib\site-packages\numpy\__init__.py", line 305, in __getattr__
    raise AttributeError(__former_attrs__[attr])
AttributeError: module 'numpy' has no attribute 'int'.
修改
#            self.batch_shapes = np.ceil(np.array(shapes) * img_size / stride + pad).astype(np.int) * stride
             self.batch_shapes = np.ceil(np.array(shapes) * img_size / stride + pad).astype(np.int_) * stride
 所有的np.int 改为  np.int_
 
报错 
TypeError: No loop matching the specified signature and casting was found for ufunc greater
    报错那一行,把dtype=np.float64,去掉。

报错
File "D:\SoftInstall\Anaconda\envs\openmmlab\lib\site-packages\torch\_tensor.py", line 757, 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.

意思是:如果想把CUDA tensor格式的数据改成numpy时
,需要先将其转换成cpu float-tensor随后再转到numpy格式。 numpy不能读取CUDA tensor 需要将它转化为 CPU tensor

   #            return self.numpy()   #原来的代码
            return self.cpu().numpy()   #修改后代码

        4. YOLOv5训练不显示GFLOPs问题

 安装pip install thop ,训练时就会看到GFLOPs


 

  • 27
    点赞
  • 47
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值