yolov5 02训练模型
# 0 还原官方的源码。注意训练时需要还原yolov5-7.0-git\yolov5\models\yolo.py的配置要不训练报错# 还原到如下图所示才能进行训练#0 测试训练环境是否正常先做上面的操作还原源码# 打开Anaconda Prompt 或 Powershell Prompt 活 bash 命令行界面source activate #加载环境变量conda env list # 查看虚拟环境conda activate yolov5_py38 # activate激活虚拟环境cd D:\/YOLO/yolov5-7.0-git/yolov5python train.py # 直接运行会自动下载数据集合 可能需要安装下git conda install git# 如果可以正常下载并运行说明正常#1 放入数据集D:\YOLO\yolov5-master\data_hat_y # 创建一个data_hat_y目录存放原始数据集#1.2 数据机分类# 一般情况下采用 rtrain训练:val验证:test测试7:2:1# 创建自己的自动分类脚本# 创建一个data_hat_y 存放原始数据集文件.jpg和.txt7_2_1.py # 创建脚本读取原始数据集进行随机划分。import os, shutil, randomfrom tqdm import tqdmdef split_img(img_path, label_path, split_list):try :Data data_hat# Data是你要将要创建的文件夹路径路径一定是相对于你当前的这个脚本而言的os.mkdir(Data)train_img_dir Data /images/trainval_img_dir Data /images/valtest_img_dir Data /images/testtrain_label_dir Data /labels/trainval_label_dir Data /labels/valtest_label_dir Data /labels/test# 创建文件夹os.makedirs(train_img_dir)os.makedirs(train_label_dir)os.makedirs(val_img_dir)os.makedirs(val_label_dir)os.makedirs(test_img_dir)os.makedirs(test_label_dir)except:print(文件目录已存在)train, val, test split_listall_img os.listdir(img_path)all_img_path [os.path.join(img_path, img) for img in all_img]# all_label os.listdir(label_path)# all_label_path [os.path.join(label_path, label) for label in all_label]train_img random.sample(all_img_path, int(train * len(all_img_path)))train_img_copy [os.path.join(train_img_dir, img.split(\\)[-1]) for img in train_img]train_label [toLabelPath(img, label_path) for img in train_img]train_label_copy [os.path.join(train_label_dir, label.split(\\)[-1]) for label in train_label]for i in tqdm(range(len(train_img)), desctrain , ncols80, unitimg):_copy(train_img[i], train_img_dir)_copy(train_label[i], train_label_dir)all_img_path.remove(train_img[i])val_img random.sample(all_img_path, int(val / (val test) * len(all_img_path)))val_label [toLabelPath(img, label_path) for img in val_img]for i in tqdm(range(len(val_img)), descval , ncols80, unitimg):_copy(val_img[i], val_img_dir)_copy(val_label[i], val_label_dir)all_img_path.remove(val_img[i])test_img all_img_pathtest_label [toLabelPath(img, label_path) for img in test_img]for i in tqdm(range(len(test_img)), desctest , ncols80, unitimg):_copy(test_img[i], test_img_dir)_copy(test_label[i], test_label_dir)def _copy(from_path, to_path):shutil.copy(from_path, to_path)def toLabelPath(img_path, label_path):img img_path.split(\\)[-1]label img.split(.jpg)[0] .txtreturn os.path.join(label_path, label)def main():img_path data_hat_y\JPEGImages # 图片输入目录.jpglabel_path data_hat_y\Annotations # 标注输入目录.txtsplit_list [0.7, 0.2, 0.1] # 数据集划分比例[train:val:test]# split_list [0.8, 0.2] # 数据集划分比例[train:val]split_img(img_path, label_path, split_list)if __name__ __main__:main()#1.3 运行脚本python 7_2_1.py # 等待执行完成#1.4 执行脚本后自动生成如下文件夹D:\YOLO\yolov5-master\data_hat # 自动生成data_hat目录# 拷贝照片images.jpg和标注文件labels.txt到该目录# 文件夹名尽量是images和labels注意大小写# 具体内容可参考下图#2 修改配置文件yolov5\data # 进入目录# 把coco128.yaml文件备份一份然后修改内容coco128.yaml # 就使用这个名字这样就不用修改训练文件了path: data_hat # 相对train.py的路径放置下列目录的前缀train: images/train # 训练集图片路径val: images/val # 验证集图片路径test: images/test # 测试集nc: 2 # 分类数量names: [hat,person] # 分类名称要和实际标注的名称对应#3 保证预训练模型已经在yolov5的根目录没有的话需要下载https://github.com/ultralytics/yolov5 # 下载权重文件# 默认使用yolov5s.pt模型D:\YOLO\yolov5-master\ # 放入目录#4 修改yolov5/train.py 按照以上配置可不用修改直接运行# 按照以上方法修改可以直接开始训练# 如果需要修改仅修改一下内容--weights # 初始化的权重文件的路径地址默认使用yolov5s.pt--cfg # 模型yaml文件的路径地址--data # 数据yaml文件的路径地址默认使用data/coco128.yaml--hyp # 超参数文件路径地址--epochs # 训练轮次默认100轮显卡好可训练300轮--batch-size # 喂入批次文件的多少默认16根据显卡性能来太大会报错--img-size # 输入图片尺寸--rect # 是否采用矩形训练默认False--resume # 接着打断训练上次的结果接着训练--nosave # 不保存模型默认False--notest # 不进行test默认False--noautoanchor # 不自动调整anchor默认False--evolve # 是否进行超参数进化默认False--bucket # 谷歌云盘bucket一般不会用到--cache-images # 是否提前缓存图片到内存以加快训练速度默认False--image-weights # 使用加权图像选择进行训练--device # 训练的设备cpu0(表示一个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 # 模型目录是否存在不存在就创建#5 开始训练conda activate yolov5_py38python train.py --device 0 # 直接运行开始训练需要还原yolov5-7.0-git\yolov5\models\yolo.py配置要不训练报错python train.py--resume #从中断的次数继续训练python train.py --resume runs/train/exp11/weights/last.ptpython -m torch.distributed.run --nproc_per_node 8 --master_port 1 train.py --device 0,1,2,3,4,5,6,7 # 官方推荐多GPU训练nohup python -m torch.distributed.run --nproc_per_node 8 --master_port 1 train.py --device 0,1,2,3,4,5,6,7 output.log 21 # 官方推荐多GPU训练后台不可用# yolov5会自动收敛如果不自动收敛可以继续增加训练次数继续第一次的pt文件训练export CUDA_VISIBLE_DEVICES0,1,2,3,4,5,6,7# 训练参数的含义解释# 第一排 训练Epoch # 训练过程中的迭代次数即完成了多少个epoch。GPU_mem # 显内使用情况单位GB。box_loss # 模型预测出的bounding box的平均损失值。关键参数越低越好obj_loss # 模型预测出的objectness的平均损失值。cls_loss # 模型预测出的分类的平均损失值。total # 所有损失值的总和即boxobjcls。labels # 每个batch中标注的物体数量的平均值。Size # 输入模型的图像的大小像素。# 这些参数的意义可以帮助训练者监控模型的训练过程以便在必要时进行调整和优化。# 第二排 测试Class # 检测的目标类别。Images # 测试集中包含该类别的图像数量。Labels # 测试集中该类别物体的真实标注数量。P # 该类别的预测精确度precision即正确预测的物体数量占所有预测的物体数量的比例。R # 该类别的召回率recall即正确预测的物体数量占所有真实物体数量的比例。mAP50 # 平均精度均值mean average precision的值即在IoU阈值为0.5时的平均精度。mAP50-95 # 在IoU阈值从0.5到0.95的范围内所有阈值的平均精度的均值。# 这些指标的意义是P和R可以帮助评估模型的分类和检测能力mAP则综合了模型在不同IoU阈值下的表现是评估模型性能的主要指标之一。#6 推理测试D:\YOLO\yolov5-master\runs\train\exp # 自动生成detect.pypython detect.py --source rtsp://admin:cetc12345192.168.50.234:554/h264/ch1/main/av_stream --weights runs/train/exp3/weights/best.pt--conf-thres 0.25python detect.py --source rtsp://admin:admin192.168.50.214:8554/live --weights runs/train/exp/weights/best.pt--conf-thres 0.25# 连rtsp测试模型python detect.py --source rtsp://admin:cetc12345192.168.50.231:554/h264/ch1/main/av_stream --weights runs/train/exp18/weights/best.pt--conf-thres 0.25python detect.py --source data_police_y/mv1.mp4 --weights runs/train/exp18/weights/best.pt--conf-thres 0.25python detect.py --source rtsp://admin:admin192.168.50.219:8554/live --weights runs/train/exp3/weights/best.pt --conf-thres 0.25python detect.py --source rtsp://admin:cetc12345192.168.50.234:554/h264/ch1/main/av_stream --weights runs/train/smoking_calling_337sl/weights/best.pt --conf-thres 0.25python detect.py --source rtsp://admin:cetc12345192.168.50.234:554/h264/ch1/main/av_stream --weights runs/train/secure_127sl/weights/best.pt --conf-thres 0.25python detect.py --source rtsp://admin:cetc12345192.168.50.234:554/h264/ch1/main/av_stream --weights runs/train/secure_127sl/weights/secure_127sl.onnx --conf-thres 0.25python detect.py --source rtsp://admin:cetc12345192.168.50.234:554/h264/ch1/main/av_stream --weights runs/train/secure_127sl/weights/best.onnx --conf-thres 0.25python detect.py --source rtsp://admin:cetc12345192.168.50.234:554/h264/ch1/main/av_stream --weights yolov5s.pt --conf-thres 0.25python detect.py --source rtsp://admin:cetc12345192.168.50.234:554/h264/ch1/main/av_stream --weights yolov5s.onnx --conf-thres 0.25# 错误处理File D:\ProgramData\anaconda3\envs\yolov5_py38\lib\site-packages\torch\_tensor.py, line 864, in splitreturn torch._VF.split_with_sizes(self, split_size, dim)IndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1)D:\YOLO\yolov5-7.0-git\yolov5\utils\loss.py #