记录下小白的我学习python yolov5的过程
本人想学这个纯属个人爱好,这篇博客只为记录过程,方便自己查阅
一、环境搭建
环境这里就不说了 根据b站大佬 《炮哥带你学》 视频有非常非常详细的教程跟着搭就完了
二、打标练习
持续关注《炮哥带你学有详细的打标教程 labelimg教程》
三、pip下载yolov5时遇到的坑
pip install -r requirements.txt 使用这段去下载yolov5需要的依赖时报错了
error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build
--这个错误大概意思是要安装一个微软环境
解决方法 某度搜这个:
# Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools"的解决办法
下载完成后,我们得到了文件mu_visual_cpp_build_tools_2015_update_3_x64_dvd_dfd9a39c.iso,解压后,双击VisualCppBuildTools_Full.exe即可自动进行安装。
如果下载完成 将会得到提示
Successfully built pycocotools Installing collected packages: pyasn1, rsa, pyasn1-modules, oauthlib, cachetools, requests-oauthlib, google-auth, torch, tensorboard-plugin-wit, tensorboard-data-server, protobuf, markdown, grpcio, google-auth-oauthlib, absl-py, tor
chvision, thop, tensorboard, pycocotools, opencv-python
四、官方提供的预选权重文件说明
我个人大概对权重的理解就是,一些选择的比重,如果你自己不适用官方提供的,也可以训练,
只不过可能效率会没有官方已经配置好的一些比重,要更容易达到你想要的识别目的,
权重文件放在yolov5项目根目录下的/weights文件夹下即可。
到这一步基本上 训练的准备要素就完成了 [训练集 + 预选权重文件]
一、开始配置Yolov5文件
二、配置预选权重文件
三、配置train.py 训练文件 找到__main__ 主函数位置以下是参数说明
"""
opt模型主要参数解析:
--weights:初始化的权重文件的路径地址
--cfg:模型yaml文件的路径地址
--data:数据yaml文件的路径地址
--hyp:超参数文件路径地址
--epochs:训练轮次
--batch-size:喂入批次文件的多少
--img-size:输入图片尺寸
--rect:是否采用矩形训练,默认False
--resume:接着打断训练上次的结果接着训练
--nosave:不保存模型,默认False
--notest:不进行test,默认False
--noautoanchor:不自动调整anchor,默认False
--evolve:是否进行超参数进化,默认False
--bucket:谷歌云盘bucket,一般不会用到
--cache-images:是否提前缓存图片到内存,以加快训练速度,默认False
--image-weights:使用加权图像选择进行训练
--device:训练的设备,cpu;0(表示一个gpu设备cuda:0);0,1,2,3(多个gpu设备)
--multi-scale:是否进行多尺度训练,默认False
--single-cls:数据集是否只有一个类别,默认False
--adam:是否使用adam优化器
--sync-bn:是否使用跨卡同步BN,在DDP模式使用
--local_rank:DDP参数,请勿修改
--workers:最大工作核心数
--project:训练模型的保存位置
--name:模型保存的目录名称
--exist-ok:模型目录是否存在,不存在就创建
"""
parser = argparse.ArgumentParser()
parser.add_argument('--weights', type=str, default='yolov5s.pt', help='initial weights path')
parser.add_argument('--cfg', type=str, default='', help='model.yaml path')
parser.add_argument('--data', type=str, default='data/coco128.yaml', help='data.yaml path')
parser.add_argument('--hyp', type=str, default='data/hyp.scratch.yaml', help='hyperparameters path')
parser.add_argument('--epochs', type=int, default=300)
parser.add_argument('--batch-size', type=int, default=16, help='total batch size for all GPUs')
parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='[train, test] image sizes')
parser.add_argument('--rect', action='store_true', help='rectangular training')
parser.add_argument('--resume', nargs='?', const=True, default=False, help='resume most recent training')
parser.add_argument('--nosave', action='store_true', help='only save final checkpoint')
parser.add_argument('--notest', action='store_true', help='only test final epoch')
parser.add_argument('--noautoanchor', action='store_true', help='disable autoanchor check')
parser.add_argument('--evolve', action='store_true', help='evolve hyperparameters')
parser.add_argument('--bucket', type=str, default='', help='gsutil bucket')
parser.add_argument('--cache-images', action='store_true', help='cache images for faster training')
parser.add_argument('--image-weights', action='store_true', help='use weighted image selection for training')
parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
parser.add_argument('--multi-scale', action='store_true', help='vary img-size +/- 50%%')
parser.add_argument('--single-cls', action='store_true', help='train multi-class data as single-class')
parser.add_argument('--adam', action='store_true', help='use torch.optim.Adam() optimizer')
parser.add_argument('--sync-bn', action='store_true', help='use SyncBatchNorm, only available in DDP mode')
parser.add_argument('--local_rank', type=int, default=-1, help='DDP parameter, do not modify')
parser.add_argument('--workers', type=int, default=8, help='maximum number of dataloader workers')
parser.add_argument('--project', default='runs/train', help='save to project/name')
parser.add_argument('--entity', default=None, help='W&B entity')
parser.add_argument('--name', default='exp', help='save to project/name')
parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
parser.add_argument('--quad', action='store_true', help='quad dataloader')
parser.add_argument('--linear-lr', action='store_true', help='linear LR')
parser.add_argument('--label-smoothing', type=float, default=0.0, help='Label smoothing epsilon')
parser.add_argument('--upload_dataset', action='store_true', help='Upload dataset as W&B artifact table')
parser.add_argument('--bbox_interval', type=int, default=-1, help='Set bounding-box image logging interval for W&B')
parser.add_argument('--save_period', type=int, default=-1, help='Log model after every "save_period" epoch')
parser.add_argument('--artifact_alias', type=str, default="latest", help='version of dataset artifact to be used')
opt = parser.parse_args()
五、配置参数遇到的坑
当我拉高 batch-size时 超过2就会报这个错 页面文件太小,我去搜了一下,原来是我PyCharm所在的D盘,分配的虚拟内存太小,我按照网上的方法,进入高级系统设置,给D盘分配了10个虚拟内存,之后我直接就可以把batch-size拉到30了,线程数,我开了16线程,因为我的cpu支持最大16线程。
六、下面晒一下我目前配置的参数 是针对我现在的配置的 it12600k + gtx2070 显存8g
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--weights', type=str, default='', help='initial weights path')
parser.add_argument('--cfg', type=str, default='models/hat.yaml', help='model.yaml path')
parser.add_argument('--data', type=str, default='data/mydata.yaml', help='data.yaml path')
parser.add_argument('--hyp', type=str, default='data/hyp.scratch.yaml', help='hyperparameters path')
parser.add_argument('--epochs', type=int, default=50)
parser.add_argument('--batch-size', type=int, default=30, help='total batch size for all GPUs')
parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='[train, test] image sizes')
parser.add_argument('--rect', action='store_true', help='rectangular training')
parser.add_argument('--resume', nargs='?', const=True, default=False, help='resume most recent training')
parser.add_argument('--nosave', action='store_true', help='only save final checkpoint')
parser.add_argument('--notest', action='store_true', help='only test final epoch')
parser.add_argument('--noautoanchor', action='store_true', help='disable autoanchor check')
parser.add_argument('--evolve', action='store_true', help='evolve hyperparameters')
parser.add_argument('--bucket', type=str, default='', help='gsutil bucket')
parser.add_argument('--cache-images', action='store_true', help='cache images for faster training')
parser.add_argument('--image-weights', action='store_true', help='use weighted image selection for training')
parser.add_argument('--device', default='0', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
parser.add_argument('--multi-scale', action='store_true', help='vary img-size +/- 50%%')
parser.add_argument('--single-cls', action='store_true', help='train multi-class data as single-class')
parser.add_argument('--adam', action='store_true', help='use torch.optim.Adam() optimizer')
parser.add_argument('--sync-bn', action='store_true', help='use SyncBatchNorm, only available in DDP mode')
parser.add_argument('--local_rank', type=int, default=-1, help='DDP parameter, do not modify')
parser.add_argument('--workers', type=int, default=16, help='maximum number of dataloader workers')
parser.add_argument('--project', default='runs/train', help='save to project/name')
parser.add_argument('--entity', default=None, help='W&B entity')
parser.add_argument('--name', default='exp', help='save to project/name')
parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
parser.add_argument('--quad', action='store_true', help='quad dataloader')
parser.add_argument('--linear-lr', action='store_true', help='linear LR')
parser.add_argument('--label-smoothing', type=float, default=0.0, help='Label smoothing epsilon')
parser.add_argument('--upload_dataset', action='store_true', help='Upload dataset as W&B artifact table')
parser.add_argument('--bbox_interval', type=int, default=-1, help='Set bounding-box image logging interval for W&B')
parser.add_argument('--save_period', type=int, default=-1, help='Log model after every "save_period" epoch')
parser.add_argument('--artifact_alias', type=str, default="latest", help='version of dataset artifact to be used')
opt = parser.parse_args()
六、 当训练结束后,打开detect.py文件 按照以下说明配置
if __name__ == '__main__':
parser = argparse.ArgumentParser()
# 这里填写你训练结束后的权重文件路径 训练结束后runs/train/exp 会生成一个weights文件夹/best.pt 就是训练后的权重文件
parser.add_argument('--weights', nargs='+', type=str, default='weights/best.pt', help='model.pt path(s)')
# 这个位置配置参数 0 代表启用摄像头 如果启用摄像头出错还需要额外去utils下的datasets.py 找到279行 将url转为字符串格式
# 如果是视频或者普通图片直接写地址即可
parser.add_argument('--source', type=str, default='0', help='source') # file/folder, 0 for webcam
parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')
parser.add_argument('--conf-thres', type=float, default=0.25, help='object confidence threshold')
parser.add_argument('--iou-thres', type=float, default=0.45, help='IOU threshold for NMS')
parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
# 是否需要查看结果 默认我们改为default True查看
parser.add_argument('--view-img', action='store_true', help='display results',default=True)
parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3')
parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
parser.add_argument('--augment', action='store_true', help='augmented inference')
parser.add_argument('--update', action='store_true', help='update all models')
parser.add_argument('--project', default='runs/detect', help='save results to project/name')
parser.add_argument('--name', default='exp', help='save results to project/name')
parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
opt = parser.parse_args()
print(opt)
check_requirements(exclude=('pycocotools', 'thop'))
七、以上操作完成基本上就已经可以检测到了这边放一些我验证的结果集
视频也是没问题的,包括摄像头我都测试过了,因为我这个模型只训练了1个小时,所以识别度还是差点意思
八、重复训练
例如我这次训练只持续了1小时,效果不是很满意,我想继续这个模型训练怎么办?
parser.add_argument('--resume', nargs='?', const=True, default=True, help='resume most recent training')
可以把第一次训练完毕的 比如我第一次训练50次 会在runs/exp/weights文件夹下方 生成一个best.pt文件 这个文件可以用于你下次训练这个模型的预选权重文件 也就是这段代码
parser.add_argument('--weights', type=str, default='填你的best.pt路径', help='initial weights path')
九、pywin32安装失败等一系列问题 我是conda管理虚拟环境 安装了半天 不是报找不到模块就是各种错误 最后这样操作终于好了
# pip卸载pywin32
pip uninstall pywin32
# conda 卸载pywin32
conda uninstall pywin32
# 卸载完成后再重新安装即可
一定要按照步骤一个一个卸载然后安装 就好了 搞了我几个小时真的吐x 网上说各种方法的都有 亲测这个有效
十、payCharm 终端环境选择CMD
今天在下依赖的时候明明依赖下好了,但是就是检测不到
后来发现是虚拟环境的问题,conda没active激活,
所以将paycharm的默认终端更改成cmd 就会自动激活虚拟环境了,就不需要一直conda active了