yolov5 02训练模型
2026/5/1 7:12:04 网站建设 项目流程

# 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/yolov5

python 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和.txt)

7_2_1.py # 创建脚本读取原始数据集,进行随机划分。

++++++++++++++++++++++++

import os, shutil, random

from tqdm import tqdm

def split_img(img_path, label_path, split_list):

try :

Data = 'data_hat'

# Data是你要将要创建的文件夹路径(路径一定是相对于你当前的这个脚本而言的)

os.mkdir(Data)

train_img_dir = Data + '/images/train'

val_img_dir = Data + '/images/val'

test_img_dir = Data + '/images/test'

train_label_dir = Data + '/labels/train'

val_label_dir = Data + '/labels/val'

test_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_list

all_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)), desc='train ', ncols=80, unit='img'):

_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)), desc='val ', ncols=80, unit='img'):

_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_path

test_label = [toLabelPath(img, label_path) for img in test_img]

for i in tqdm(range(len(test_img)), desc='test ', ncols=80, unit='img'):

_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] + '.txt'

return os.path.join(label_path, label)

def main():

img_path = 'data_hat_y\JPEGImages' # 图片输入目录.jpg

label_path = 'data_hat_y\Annotations' # 标注输入目录.txt

split_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 # 训练的设备,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 # 模型目录是否存在,不存在就创建

#5 开始训练

conda activate yolov5_py38

python 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.pt

python -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 2>&1 & # 官方推荐多GPU训练(后台不可用)

# yolov5会自动收敛,如果不自动收敛可以继续增加训练次数,继续第一次的pt文件训练

export CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7

# 训练参数的含义解释

# 第一排 训练

Epoch # 训练过程中的迭代次数(即完成了多少个epoch)。

GPU_mem # 显内使用情况,单位GB。

box_loss # 模型预测出的bounding box的平均损失值。关键参数,越低越好

obj_loss # 模型预测出的objectness的平均损失值。

cls_loss # 模型预测出的分类的平均损失值。

total # 所有损失值的总和,即box+obj+cls。

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.py

python detect.py --source rtsp://admin:cetc12345@192.168.50.234:554/h264/ch1/main/av_stream --weights runs/train/exp3/weights/best.pt--conf-thres 0.25

python detect.py --source rtsp://admin:admin@192.168.50.214:8554/live --weights runs/train/exp/weights/best.pt--conf-thres 0.25

# 连rtsp测试模型

python detect.py --source rtsp://admin:cetc12345@192.168.50.231:554/h264/ch1/main/av_stream --weights runs/train/exp18/weights/best.pt--conf-thres 0.25

python detect.py --source data_police_y/mv1.mp4 --weights runs/train/exp18/weights/best.pt--conf-thres 0.25

python detect.py --source rtsp://admin:admin@192.168.50.219:8554/live --weights runs/train/exp3/weights/best.pt --conf-thres 0.25

python detect.py --source rtsp://admin:cetc12345@192.168.50.234:554/h264/ch1/main/av_stream --weights runs/train/smoking_calling_337sl/weights/best.pt --conf-thres 0.25

python detect.py --source rtsp://admin:cetc12345@192.168.50.234:554/h264/ch1/main/av_stream --weights runs/train/secure_127sl/weights/best.pt --conf-thres 0.25

python detect.py --source rtsp://admin:cetc12345@192.168.50.234:554/h264/ch1/main/av_stream --weights runs/train/secure_127sl/weights/secure_127sl.onnx --conf-thres 0.25

python detect.py --source rtsp://admin:cetc12345@192.168.50.234:554/h264/ch1/main/av_stream --weights runs/train/secure_127sl/weights/best.onnx --conf-thres 0.25

python detect.py --source rtsp://admin:cetc12345@192.168.50.234:554/h264/ch1/main/av_stream --weights yolov5s.pt --conf-thres 0.25

python detect.py --source rtsp://admin:cetc12345@192.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 split

return 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 #

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询