Yolo目标检测——从YOLO V1~V5
经典目标检测方法

one-stage:
直接将目标检测转化为回归问题,通过单个神经网络同时预测目标的类别和位置,无需候选框生成步骤。
one-stage的优缺点:
优点:识别速度非常快,适合做实时检测任务
缺点:正确率相比较低
two-stage:
以 Faster R-CNN、Mask R-CNN 为代表,核心流程是先生成候选框,再对候选框分类回归:
这种方法主要包括两个阶段:
第一阶段:生成候选框。这通常通过一个类似于Selective Search或EdgeBoxes等区域提名算法来实现,该算法从输入图像中生成多个候选框。每个候选框都会经过一个CNN模型进行特征提取,然后通过分类器进行过滤,保留与目标物体更相似的候选框。
第二阶段:在保留的候选框上进行精细的分类和回归。这个阶段通常使用另一个CNN模型或类似SVM的分类器来进行分类和回归。对于每个候选框,可能需要预测物体的类别、位置和大小等。 代表性的两阶段目标检测器包括R-CNN系列,以及其改进版本Fast R-CNN、Faster R-CNN和Mask R-CNN等。
two-stage的优缺点:
优点:正确率比较高,识别效果理想
缺点:识别速度比较慢,通常达到5FPS
目标检测核心评价指标:mAP 与 IoU
Map指标的介绍
英文全称是(Mean Average Precision),是综合衡量检测效果的核心指标,其计算基于 IoU、精确率(Precision)和召回率(Recall)。
IoU
实际上就是预测框和真实框面积的交集与并集的比值

IoU 值越接近 1,代表预测框越精准,通常将IoU>0.5作为检测正确的基础阈值。
精确率与召回率
基于混淆矩阵的四个核心指标计算:
-
TP(真阳性):真实有目标,预测也有目标且正确;
-
FP(假阳性):真实无目标,预测有目标;
-
FN(假阴性):真实有目标,预测无目标;
-
TN(真阴性):真实无目标,预测也无目标。
精确率:预测为正的结果中,真实为正的比例,反映 “预测的结果中有多少是正确的”

召回率:真实为正的结果中,被预测为正的比例,反映 “真实的结果中有多少是预测正确的”

mAP 与衍生指标
mAP 是所有类别AP(Average Precision) 的平均值,AP 是根据不同置信度阈值绘制的 “精确率 - 召回率曲线” 下的面积,面积越大则性能越好。

mAP50:IoU 阈值固定为 0.5 时的平均精度,是基础评价标准
mAP50 - 95:IoU 阈值从 0.5 到 0.95,以 0.05 为步长的平均精度,考虑了不同重叠程度的检测效果,是更严格的评价指标,数值通常低于 mAP50。
置信度
表示某个预测框中存在目标的可能性大小,是一个介于 0 到 1 之间的数值。
例如,一个预测框的目标存在置信度为 0.8,意味着模型有 80% 的把握认为该预测框中包含一个目标。
YOLO系列
YOLO(You Only Look Once)是一种基于深度学习的目标检测算法,由Joseph Redmon等人于2016年提出。
YOLO 系列的核心思想始终是将输入图像划分为 S×S 网格,每个网格负责预测其中心落在网格内的目标,并通过回归直接输出目标的位置(x,y,w,h)和类别概率。
此外,YOLO算法还采用了多尺度特征融合的技术,使得算法能够在不同尺度下对目标进行检测。 相比于传统的目标检测算法,如R-CNN、Fast R-CNN和Faster R-CNN等,YOLO算法具有更快的检测速度和更高的准确率。这得益于其端到端训练方式和单阶段检测的特性,使其可以同时处理分类和定位任务,避免了传统方法中的多阶段处理过程。因此,YOLO算法广泛应用于实时目标检测和自动驾驶等领域。
YOLO v1
YOLOv1 是 经典的one-stage方法,首次实现了端到端的目标检测训练与推理,将检测问题完全转化为回归问题。
核心思想:
将一幅图像分成SxS个网格(grid cell),如果某个object的中心 落在这个网格中,则这个网格就负责预测这个object。

网络架构:
网络结构借鉴了 GoogLeNet 。24个卷积层+2个全链接层。用 “1×1 卷积层 + 3×3 卷积层” 替代 Inception 模块,输入图像尺寸为 448×448,最终输出7×7×30的特征图:
-
7×7:将图像划分为 7×7 个网格;
-
30:每个网格包含 2 个预测框,每个预测框对应 5 个信息(x,y,w,h, 置信度),剩余 20 个为 VOC 数据集的 20 个类别概率。
其中,x、y 为预测框中心相对于网格的归一化坐标(0-1),w、h 为预测框宽高相对于图像的归一化值(0-1)。
损失函数:
YOLO的损失就包括三部分:位置误差,confidence误差,分类误差。
损失函数的设计目标就是让坐标(x,y,w,h),confidence,classification这个三个方面达到很好的平衡。
非极大值抑制
用通俗的话来说,就是在一堆重叠、重复的检测框里:只保留置信度最高的框,删掉和它重叠太多的框。
YOLO V1存在的优缺点:
优点:速度快,简单
问题1:每个cell只预测1个类别,如果重叠无法解决
问题2:小物体检测效果一般,长宽比可选,但单一。
YOLO v2
YOLOv2 在 V1 基础上做了大量针对性改进,实现了速度和精度的双重提升,核心关键词是 “高分辨率、锚框、多尺度”。
网络架构:

聚类提取先验框

流程:
在模型训练之前,提前把训练集的标签值提取出来,通过k-means聚类的方法,聚类出5个类别。结果当作是先验框。 最后在进行模型训练。
感受野
概述来说就是特征图上的点,能看到原始图像多大的区域

核心改进点
1、加入 Batch Normalization:舍弃 Dropout,所有卷积层后加入归一化,使网络收敛更易,mAP 提升 2%;
2、高分辨率分类器:V1 训练用 224×224,测试用 448×448,易导致模型 “水土不服”;V2 额外进行 10 次 448×448 微调,mAP 提升约 4%;
3、引入锚框(Anchor Box):通过 K-means 聚类训练集标签,得到 5 种先验框,解决 V1 长宽比单一问题(先验框不是直接按照长宽固定比给定),提升目标定位精度;
4、直接位置预测(Directed Location Prediction):
Directed Location Prediction是一种方法,其目的是进行位置微调,预测偏移量。它用于限制偏移量,以防止在训练时出现发散。这种方法预测的是相对位置,即相对于网格的偏移量。模型输出的值为tx、ty
预测相对网格的偏移量,限制偏移范围,避免训练时发散,提升模型稳定性;
5、新网络 Darknet-19:无全连接层,5 次降采样输出 13×13 网格,用 1×1 卷积减少参数,提升特征提取效率;
6、多尺度训练:整个网络结构不包含全连接层,因此输入图片的大小可以任意输入图像尺寸可在 320×320 到 608×608 之间动态调整(需被 32 整除),适配不同尺度目标检测。
YOLO v3
终于到 V3 了,最大的改进就是网络结构,使其更适合小目标检测
特征做的更细致,融入多持续特征图信息来预测不同规格物体
先验框更丰富了,3 种 scale,每种 3 个规格,一共 9 种
softmax 改进,预测多标签任务
网络架构:

9种尺度的先验框
YOLO3延续了K-means聚类得到先验框的尺寸方法,为每种下采样尺度设定3种先验框,总共聚类出9种尺寸的先验框。
在COCO数据集这9个先验框是:(10x13),(16x30),(33x23),(30x61),(62x45),(59x119),(116x90),(156x198),(373x326)。
在最小的13*13特征图上(有最大的感受野)应用较大的先验框(116x90),(156x198),(373x326),适合检测较大的对象。
中等的26*26特征图上(中等感受野)应用中等的先验框(30x61),(62x45),(59x119),适合检测中等大小的对象。
较大的52*52特征图上(较小的感受野)应用较小的先验框(10x13),(16x30),(33x23),适合检测较小的对象。
核心改进点
-
新网络 Darknet-53:引入残差连接(ResNet),堆叠 53 个卷积层,无池化和全连接层,通过步长为 2 的卷积实现下采样,解决深层网络梯度消失问题,提升特征提取能力;
-
多尺度检测:输出 3 个尺度的特征图(13×13、26×26、52×52),对应不同感受野,适配大、中、小目标:
-
13×13(大感受野):搭配大锚框,检测大目标;
-
26×26(中等感受野):搭配中等锚框,检测中目标;
-
52×52(小感受野):搭配小锚框,检测小目标;
-
-
锚框数量增加:通过 K-means 聚类得到 9 种锚框,3 个尺度各分配 3 种,覆盖更多目标尺寸;
-
分类器优化:用多个独立 Logistic 分类器替代 Softmax,支持多标签分类(如一个目标同时属于 “人” 和 “行人”),每个类别通过 Sigmoid 函数输出 0-1 的概率值;
-
特征融合:结合 FPN(特征金字塔网络)的自顶向下和自底向上路径,融合浅层和深层特征,提升小目标检测精度。
数据标注和模型配置
理论之外,YOLO 的核心价值在于落地应用,以下以 YOLOv3 为例,介绍基于 PyTorch 框架的目标检测实战流程,核心步骤包括数据标注、标签格式转换、模型配置
1. 数据标注:Labelme 工具使用
数据标注是目标检测的基础,Labelme 是开源的图像标注工具,支持矩形框标注,步骤如下:
-
安装:
pip install labelme pyqt5 pillow; -
启动:cmd 中输入
labelme,选择待标注图像文件夹; -
标注:绘制目标矩形框,添加类别标签,标注结果默认保存为JSON 格式,包含目标坐标和类别信息。
2. 标签格式转换:JSON→YOLO 格式
YOLO 要求标签为txt 格式,每行对应一个目标,内容为类别ID x y w h(x,y 为目标中心归一化坐标,w,h 为目标宽高归一化值),需将 Labelme 生成的 JSON 文件转换为该格式:
-
编写转换脚本(如 json2yolo.py),读取 JSON 中的坐标信息,计算归一化值;
-
转换后的 txt 文件与对应图像同名,保存在
data/custom/labels目录下。
3. 模型配置文件设置
基于 PyTorch-YOLOv3 框架,需修改配置文件适配自定义数据集:
-
生成自定义配置文件:通过
bash create_custom_model.sh 类别数,自动生成yolov3-custom.cfg,替换原 cfg 文件; -
修改类别名称:将
classes.names文件中的类别改为自定义类别,顺序与类别 ID 一致; -
配置数据集路径:修改
custom.data,指定训练集 / 验证集路径、类别数、类别名称文件路径; -
编写训练 / 验证集列表:在
train.txt/val.txt中写入图像的绝对 / 相对路径。
YOLO v4
YOLOv4 更换了作者,但延续了 YOLO 的核心思想,吸收了当前计算机视觉领域的主流优化策略,在不降低推理速度的前提下,大幅提升检测精度,核心是 “Bag of Freebies”(只增加训练成本,不影响推理速度)
核心改进点
1、数据增强策略
-
马赛克增强(Mosaic):将 4 张图像拼接成 1 张训练,丰富目标背景,提升模型泛化能力;
-
随机擦除、Hide and Seek:随机屏蔽图像区域,增强模型对局部特征的学习;
-
自对抗训练(SAT):引入噪音增加训练难度,提升模型鲁棒性。
2、正则化与标签优化
-
DropBlock:替代 Dropout,随机屏蔽特征图的连续区域,减少冗余连接,缓解过拟合;
-
标签平滑:将硬标签(如 [0,1])转化为软标签(如 [0.05,0.95]),降低模型过自信,提升泛化能力。
DropBlock是谷歌在2018年提出的一种用于卷积神经网络(CNN)的正则化方法。这是一种用于解决过拟合问题的技术,在训练神经网络时非常有用。过拟合问题是指在训练集上表现很好,但在测试集上表现不佳的问题。
相比于传统的Dropout技术,DropBlock不是随机屏蔽掉一部分特征(注意是对特征图进行屏蔽),而是随机屏蔽掉多个部分连续的区域。这种方法有助于减少神经网络中的冗余连接,从而提高模型的泛化能力。
3、损失函数优化:从 IoU 损失逐步升级为GIoU→DIoU→CIoU 损失,解决 IoU 损失在目标框不重叠时梯度为 0 的问题,同时考虑目标框的重叠面积、中心点距离、长宽比,让预测框更精准。
4、NMS 优化:引入DIoU-NMS和Soft-NMS,替代传统 NMS,考虑目标框中心点距离,避免重叠目标被误删,提升检测召回率。

非极大值抑制的改进
NMS用于过滤掉冗余的检测框并保留最准确的框。在目标检测中,算法会输出多个检测框,但有些框可能是冗余的,这时候就需要进行后处理。
DIOU-NMS和原始的NMS不同,DIoU-NMS不仅考虑了IoU的值,还考虑了两个Box中心点之间的距离,使用了新的公式决定一个Box是否被删除:

Soft-NMS
传统的NMS存在一定的问题:如果一个物体在另一个物体重叠区域出现,即当两个目标框接近时,分数更低的框就会因为与之重叠面积过大而被删掉,从而导致对该物体的检测失败并降低了算法的平均检测率。
将当前检测框得分乘以一个权重函数,该函数会衰减与最高得分检测框M有重叠的相邻检测框的分数,越是与M框高度重叠的检测框,其得分衰减越严重,为此选择高斯函数为权重函数,从而修改其删除检测框的规则。(δ通常取0.3)。
5、网络结构升级
-
骨干网络:CSPDarknet-53,结合 CSPNet 和 Darknet-53,降低内存成本,提升学习能力;

-
特征融合:SPP-Net+PAN-FPN,SPP 层提升大目标特征提取能力,PAN-FPN 实现双向特征融合,进一步优化小目标检测;

-
注意力机制:加入 SAM(空间注意力模块),聚焦图像关键区域,提升特征利用率;

-
激活函数:用 Mish 替代 ReLU,Mish 更平滑,能保留更多梯度信息,提升模型性能;

-
消除网格敏感度:在坐标回归激活函数前加入系数,解决网格边界处目标预测困难的问题。

YOLO v5
v4是偏学术上的实现 v5增加了工程上的使用,将来开发可以模仿v5版本的代码
核心特性
-
极致的工程化设计:代码结构简洁,支持自动下载权重、多平台部署(CPU/GPU/ 移动端),提供丰富的可视化工具;
-
灵活的模型规模:提供 s/m/l/x 四个版本,适配不同硬件资源,从移动端的轻量模型到服务器端的高精度模型全覆盖;
-
自动化数据处理:支持多种数据集格式(COCO/VOC/YOLO),内置数据增强、标签转换功能,降低数据准备成本;
-
高效的训练策略:支持混合精度训练、分布式训练,提升训练速度,减少显存占用;
-
丰富的生态支持:结合 Roboflow 等数据集平台,可快速获取标注好的数据集,同时支持摄像头、视频、RTSP 流等多种输入源的实时检测。
下载渠道
可以从github上下载各种版本的

项目案例:口罩检测
根据下载的yolo v5的模型,还有口罩的数据集,修改train.py下的形参,改成你需要的参数;
比如口罩检测,就分成两种,戴口罩和不带口罩,同时注意标签顺序

还可以修改形参,改成你需要的训练轮数,打包,使用什么模型等等

下面是一个完整的train.py的代码:
import argparse
import torch.distributed as dist
import torch.nn.functional as F
import torch.optim as optim
import torch.optim.lr_scheduler as lr_scheduler
import torch.utils.data
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.utils.tensorboard import SummaryWriter
import test # import test.py to get mAP after each epoch
from models.yolo import Model
from utils import google_utils
from utils.datasets import *
from utils.utils import *
mixed_precision = True
try: # Mixed precision training https://github.com/NVIDIA/apex
from apex import amp
except:
print('Apex recommended for faster mixed precision training: https://github.com/NVIDIA/apex')
mixed_precision = False # not installed
# Hyperparameters
hyp = {'optimizer': 'SGD', # ['adam', 'SGD', None] if none, default is SGD
'lr0': 0.01, # initial learning rate (SGD=1E-2, Adam=1E-3)
'momentum': 0.937, # SGD momentum/Adam beta1
'weight_decay': 5e-4, # optimizer weight decay
'giou': 0.05, # giou loss gain
'cls': 0.5, # cls loss gain
'cls_pw': 1.0, # cls BCELoss positive_weight
'obj': 1.0, # obj loss gain (*=img_size/320 if img_size != 320)
'obj_pw': 1.0, # obj BCELoss positive_weight
'iou_t': 0.20, # iou training threshold
'anchor_t': 4.0, # anchor-multiple threshold
'fl_gamma': 0.0, # focal loss gamma (efficientDet default is gamma=1.5)
'hsv_h': 0.015, # image HSV-Hue augmentation (fraction)
'hsv_s': 0.7, # image HSV-Saturation augmentation (fraction)
'hsv_v': 0.4, # image HSV-Value augmentation (fraction)
'degrees': 0.0, # image rotation (+/- deg)
'translate': 0.0, # image translation (+/- fraction)
'scale': 0.5, # image scale (+/- gain)
'shear': 0.0} # image shear (+/- deg)
def train(hyp, tb_writer, opt, device):
print(f'Hyperparameters {hyp}')
log_dir = tb_writer.log_dir if tb_writer else 'runs/evolution' # run directory
wdir = str(Path(log_dir) / 'weights') + os.sep # weights directory
os.makedirs(wdir, exist_ok=True)
last = wdir + 'last.pt'
best = wdir + 'best.pt'
results_file = log_dir + os.sep + 'results.txt'
epochs, batch_size, total_batch_size, weights, rank = \
opt.epochs, opt.batch_size, opt.total_batch_size, opt.weights, opt.local_rank
# TODO: Init DDP logging. Only the first process is allowed to log.
# Since I see lots of print here, the logging configuration is skipped here. We may see repeated outputs.
# Save run settings
with open(Path(log_dir) / 'hyp.yaml', 'w') as f:
yaml.dump(hyp, f, sort_keys=False)
with open(Path(log_dir) / 'opt.yaml', 'w') as f:
yaml.dump(vars(opt), f, sort_keys=False)
# Configure
init_seeds(2 + rank)
with open(opt.data) as f:
data_dict = yaml.load(f, Loader=yaml.FullLoader) # model dict
train_path = data_dict['train']
test_path = data_dict['val']
nc, names = (1, ['item']) if opt.single_cls else (int(data_dict['nc']), data_dict['names']) # number classes, names
assert len(names) == nc, '%g names found for nc=%g dataset in %s' % (len(names), nc, opt.data) # check
# Remove previous results
if rank in [-1, 0]:
for f in glob.glob('*_batch*.jpg') + glob.glob(results_file):
os.remove(f)
# Create model
model = Model(opt.cfg, nc=nc).to(device)
# Image sizes
gs = int(max(model.stride)) # grid size (max stride)
imgsz, imgsz_test = [check_img_size(x, gs) for x in opt.img_size] # verify imgsz are gs-multiples
# Optimizer
nbs = 64 # nominal batch size
# default DDP implementation is slow for accumulation according to: https://pytorch.org/docs/stable/notes/ddp.html
# all-reduce operation is carried out during loss.backward().
# Thus, there would be redundant all-reduce communications in a accumulation procedure,
# which means, the result is still right but the training speed gets slower.
# TODO: If acceleration is needed, there is an implementation of allreduce_post_accumulation
# in https://github.com/NVIDIA/DeepLearningExamples/blob/master/PyTorch/LanguageModeling/BERT/run_pretraining.py
accumulate = max(round(nbs / total_batch_size), 1) # accumulate loss before optimizing
hyp['weight_decay'] *= total_batch_size * accumulate / nbs # scale weight_decay
pg0, pg1, pg2 = [], [], [] # optimizer parameter groups
for k, v in model.named_parameters():
if v.requires_grad:
if '.bias' in k:
pg2.append(v) # biases
elif '.weight' in k and '.bn' not in k:
pg1.append(v) # apply weight decay
else:
pg0.append(v) # all else
if hyp['optimizer'] == 'adam': # https://pytorch.org/docs/stable/_modules/torch/optim/lr_scheduler.html#OneCycleLR
optimizer = optim.Adam(pg0, lr=hyp['lr0'], betas=(hyp['momentum'], 0.999)) # adjust beta1 to momentum
else:
optimizer = optim.SGD(pg0, lr=hyp['lr0'], momentum=hyp['momentum'], nesterov=True)
optimizer.add_param_group({'params': pg1, 'weight_decay': hyp['weight_decay']}) # add pg1 with weight_decay
optimizer.add_param_group({'params': pg2}) # add pg2 (biases)
print('Optimizer groups: %g .bias, %g conv.weight, %g other' % (len(pg2), len(pg1), len(pg0)))
del pg0, pg1, pg2
# Load Model
with torch_distributed_zero_first(rank):
google_utils.attempt_download(weights)
start_epoch, best_fitness = 0, 0.0
if weights.endswith('.pt'): # pytorch format
ckpt = torch.load(weights, map_location=device) # load checkpoint
# load model
try:
exclude = ['anchor'] # exclude keys
ckpt['model'] = {k: v for k, v in ckpt['model'].float().state_dict().items()
if k in model.state_dict() and not any(x in k for x in exclude)
and model.state_dict()[k].shape == v.shape}
model.load_state_dict(ckpt['model'], strict=False)
print('Transferred %g/%g items from %s' % (len(ckpt['model']), len(model.state_dict()), weights))
except KeyError as e:
s = "%s is not compatible with %s. This may be due to model differences or %s may be out of date. " \
"Please delete or update %s and try again, or use --weights '' to train from scratch." \
% (weights, opt.cfg, weights, weights)
raise KeyError(s) from e
# load optimizer
if ckpt['optimizer'] is not None:
optimizer.load_state_dict(ckpt['optimizer'])
best_fitness = ckpt['best_fitness']
# load results
if ckpt.get('training_results') is not None:
with open(results_file, 'w') as file:
file.write(ckpt['training_results']) # write results.txt
# epochs
start_epoch = ckpt['epoch'] + 1
if epochs < start_epoch:
print('%s has been trained for %g epochs. Fine-tuning for %g additional epochs.' %
(weights, ckpt['epoch'], epochs))
epochs += ckpt['epoch'] # finetune additional epochs
del ckpt
# Mixed precision training https://github.com/NVIDIA/apex
if mixed_precision:
model, optimizer = amp.initialize(model, optimizer, opt_level='O1', verbosity=0)
# Scheduler https://arxiv.org/pdf/1812.01187.pdf
lf = lambda x: (((1 + math.cos(x * math.pi / epochs)) / 2) ** 1.0) * 0.8 + 0.2 # cosine
scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lf)
# https://discuss.pytorch.org/t/a-problem-occured-when-resuming-an-optimizer/28822
# plot_lr_scheduler(optimizer, scheduler, epochs)
# DP mode
if device.type != 'cpu' and rank == -1 and torch.cuda.device_count() > 1:
model = torch.nn.DataParallel(model)
# SyncBatchNorm
if opt.sync_bn and device.type != 'cpu' and rank != -1:
model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model).to(device)
print('Using SyncBatchNorm()')
# Exponential moving average
ema = torch_utils.ModelEMA(model) if rank in [-1, 0] else None
# DDP mode
if device.type != 'cpu' and rank != -1:
model = DDP(model, device_ids=[rank], output_device=rank)
# Trainloader
dataloader, dataset = create_dataloader(train_path, imgsz, batch_size, gs, opt, hyp=hyp, augment=True,
cache=opt.cache_images, rect=opt.rect, local_rank=rank,
world_size=opt.world_size)
mlc = np.concatenate(dataset.labels, 0)[:, 0].max() # max label class
nb = len(dataloader) # number of batches
assert mlc < nc, 'Label class %g exceeds nc=%g in %s. Possible class labels are 0-%g' % (mlc, nc, opt.data, nc - 1)
# Testloader
if rank in [-1, 0]:
# local_rank is set to -1. Because only the first process is expected to do evaluation.
testloader = create_dataloader(test_path, imgsz_test, total_batch_size, gs, opt, hyp=hyp, augment=False,
cache=opt.cache_images, rect=True, local_rank=-1, world_size=opt.world_size)[0]
# Model parameters
hyp['cls'] *= nc / 80. # scale coco-tuned hyp['cls'] to current dataset
model.nc = nc # attach number of classes to model
model.hyp = hyp # attach hyperparameters to model
model.gr = 1.0 # giou loss ratio (obj_loss = 1.0 or giou)
model.class_weights = labels_to_class_weights(dataset.labels, nc).to(device) # attach class weights
model.names = names
# Class frequency
if rank in [-1, 0]:
labels = np.concatenate(dataset.labels, 0)
c = torch.tensor(labels[:, 0]) # classes
# cf = torch.bincount(c.long(), minlength=nc) + 1.
# model._initialize_biases(cf.to(device))
plot_labels(labels, save_dir=log_dir)
if tb_writer:
# tb_writer.add_hparams(hyp, {}) # causes duplicate https://github.com/ultralytics/yolov5/pull/384
tb_writer.add_histogram('classes', c, 0)
# Check anchors
if not opt.noautoanchor:
check_anchors(dataset, model=model, thr=hyp['anchor_t'], imgsz=imgsz)
# Start training
t0 = time.time()
nw = max(3 * nb, 1e3) # number of warmup iterations, max(3 epochs, 1k iterations)
maps = np.zeros(nc) # mAP per class
results = (0, 0, 0, 0, 0, 0, 0) # 'P', 'R', 'mAP', 'F1', 'val GIoU', 'val Objectness', 'val Classification'
scheduler.last_epoch = start_epoch - 1 # do not move
if rank in [0, -1]:
print('Image sizes %g train, %g test' % (imgsz, imgsz_test))
print('Using %g dataloader workers' % dataloader.num_workers)
print('Starting training for %g epochs...' % epochs)
# torch.autograd.set_detect_anomaly(True)
for epoch in range(start_epoch, epochs): # epoch ------------------------------------------------------------------
model.train()
# Update image weights (optional)
# When in DDP mode, the generated indices will be broadcasted to synchronize dataset.
if dataset.image_weights:
# Generate indices.
if rank in [-1, 0]:
w = model.class_weights.cpu().numpy() * (1 - maps) ** 2 # class weights
image_weights = labels_to_image_weights(dataset.labels, nc=nc, class_weights=w)
dataset.indices = random.choices(range(dataset.n), weights=image_weights,
k=dataset.n) # rand weighted idx
# Broadcast.
if rank != -1:
indices = torch.zeros([dataset.n], dtype=torch.int)
if rank == 0:
indices[:] = torch.from_tensor(dataset.indices, dtype=torch.int)
dist.broadcast(indices, 0)
if rank != 0:
dataset.indices = indices.cpu().numpy()
# Update mosaic border
# b = int(random.uniform(0.25 * imgsz, 0.75 * imgsz + gs) // gs * gs)
# dataset.mosaic_border = [b - imgsz, -b] # height, width borders
mloss = torch.zeros(4, device=device) # mean losses
if rank != -1:
dataloader.sampler.set_epoch(epoch)
pbar = enumerate(dataloader)
if rank in [-1, 0]:
print(('\n' + '%10s' * 8) % ('Epoch', 'gpu_mem', 'GIoU', 'obj', 'cls', 'total', 'targets', 'img_size'))
pbar = tqdm(pbar, total=nb) # progress bar
optimizer.zero_grad()
for i, (imgs, targets, paths, _) in pbar: # batch -------------------------------------------------------------
ni = i + nb * epoch # number integrated batches (since train start)
imgs = imgs.to(device, non_blocking=True).float() / 255.0 # uint8 to float32, 0 - 255 to 0.0 - 1.0
# Warmup
if ni <= nw:
xi = [0, nw] # x interp
# model.gr = np.interp(ni, xi, [0.0, 1.0]) # giou loss ratio (obj_loss = 1.0 or giou)
accumulate = max(1, np.interp(ni, xi, [1, nbs / total_batch_size]).round())
for j, x in enumerate(optimizer.param_groups):
# bias lr falls from 0.1 to lr0, all other lrs rise from 0.0 to lr0
x['lr'] = np.interp(ni, xi, [0.1 if j == 2 else 0.0, x['initial_lr'] * lf(epoch)])
if 'momentum' in x:
x['momentum'] = np.interp(ni, xi, [0.9, hyp['momentum']])
# Multi-scale
if opt.multi_scale:
sz = random.randrange(imgsz * 0.5, imgsz * 1.5 + gs) // gs * gs # size
sf = sz / max(imgs.shape[2:]) # scale factor
if sf != 1:
ns = [math.ceil(x * sf / gs) * gs for x in imgs.shape[2:]] # new shape (stretched to gs-multiple)
imgs = F.interpolate(imgs, size=ns, mode='bilinear', align_corners=False)
# Forward
pred = model(imgs)
# Loss
loss, loss_items = compute_loss(pred, targets.to(device), model) # scaled by batch_size
if rank != -1:
loss *= opt.world_size # gradient averaged between devices in DDP mode
if not torch.isfinite(loss):
print('WARNING: non-finite loss, ending training ', loss_items)
return results
# Backward
if mixed_precision:
with amp.scale_loss(loss, optimizer) as scaled_loss:
scaled_loss.backward()
else:
loss.backward()
# Optimize
if ni % accumulate == 0:
optimizer.step()
optimizer.zero_grad()
if ema is not None:
ema.update(model)
# Print
if rank in [-1, 0]:
mloss = (mloss * i + loss_items) / (i + 1) # update mean losses
mem = '%.3gG' % (torch.cuda.memory_cached() / 1E9 if torch.cuda.is_available() else 0) # (GB)
s = ('%10s' * 2 + '%10.4g' * 6) % (
'%g/%g' % (epoch, epochs - 1), mem, *mloss, targets.shape[0], imgs.shape[-1])
pbar.set_description(s)
# Plot
if ni < 3:
f = str(Path(log_dir) / ('train_batch%g.jpg' % ni)) # filename
result = plot_images(images=imgs, targets=targets, paths=paths, fname=f)
if tb_writer and result is not None:
tb_writer.add_image(f, result, dataformats='HWC', global_step=epoch)
# tb_writer.add_graph(model, imgs) # add model to tensorboard
# end batch ------------------------------------------------------------------------------------------------
# Scheduler
scheduler.step()
# Only the first process in DDP mode is allowed to log or save checkpoints.
if rank in [-1, 0]:
# mAP
if ema is not None:
ema.update_attr(model, include=['yaml', 'nc', 'hyp', 'gr', 'names', 'stride'])
final_epoch = epoch + 1 == epochs
if not opt.notest or final_epoch: # Calculate mAP
results, maps, times = test.test(opt.data,
batch_size=total_batch_size,
imgsz=imgsz_test,
save_json=final_epoch and opt.data.endswith(os.sep + 'coco.yaml'),
model=ema.ema.module if hasattr(ema.ema, 'module') else ema.ema,
single_cls=opt.single_cls,
dataloader=testloader,
save_dir=log_dir)
# Write
with open(results_file, 'a') as f:
f.write(s + '%10.4g' * 7 % results + '\n') # P, R, mAP, F1, test_losses=(GIoU, obj, cls)
if len(opt.name) and opt.bucket:
os.system('gsutil cp %s gs://%s/results/results%s.txt' % (results_file, opt.bucket, opt.name))
# Tensorboard
if tb_writer:
tags = ['train/giou_loss', 'train/obj_loss', 'train/cls_loss',
'metrics/precision', 'metrics/recall', 'metrics/mAP_0.5', 'metrics/mAP_0.5:0.95',
'val/giou_loss', 'val/obj_loss', 'val/cls_loss']
for x, tag in zip(list(mloss[:-1]) + list(results), tags):
tb_writer.add_scalar(tag, x, epoch)
# Update best mAP
fi = fitness(np.array(results).reshape(1, -1)) # fitness_i = weighted combination of [P, R, mAP, F1]
if fi > best_fitness:
best_fitness = fi
# Save model
save = (not opt.nosave) or (final_epoch and not opt.evolve)
if save:
with open(results_file, 'r') as f: # create checkpoint
ckpt = {'epoch': epoch,
'best_fitness': best_fitness,
'training_results': f.read(),
'model': ema.ema.module if hasattr(ema, 'module') else ema.ema,
'optimizer': None if final_epoch else optimizer.state_dict()}
# Save last, best and delete
torch.save(ckpt, last)
if (best_fitness == fi) and not final_epoch:
torch.save(ckpt, best)
del ckpt
# end epoch ----------------------------------------------------------------------------------------------------
# end training
if rank in [-1, 0]:
# Strip optimizers
n = ('_' if len(opt.name) and not opt.name.isnumeric() else '') + opt.name
fresults, flast, fbest = 'results%s.txt' % n, wdir + 'last%s.pt' % n, wdir + 'best%s.pt' % n
for f1, f2 in zip([wdir + 'last.pt', wdir + 'best.pt', 'results.txt'], [flast, fbest, fresults]):
if os.path.exists(f1):
os.rename(f1, f2) # rename
ispt = f2.endswith('.pt') # is *.pt
strip_optimizer(f2) if ispt else None # strip optimizer
os.system('gsutil cp %s gs://%s/weights' % (f2, opt.bucket)) if opt.bucket and ispt else None # upload
# Finish
if not opt.evolve:
plot_results(save_dir=log_dir) # save as results.png
print('%g epochs completed in %.3f hours.\n' % (epoch - start_epoch + 1, (time.time() - t0) / 3600))
dist.destroy_process_group() if rank not in [-1, 0] else None
torch.cuda.empty_cache()
return results
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--cfg', type=str, default='models/yolov5s.yaml', 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='', help='hyp.yaml path (optional)')
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 sizes')
parser.add_argument('--rect', action='store_true', help='rectangular training')
parser.add_argument('--resume', nargs='?', const='get_last', default=False,
help='resume from given path/to/last.pt, or most recent run if blank.')
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('--weights', type=str, default='', help='initial weights path')
parser.add_argument('--name', default='', help='renames results.txt to results_name.txt if supplied')
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 as single-class dataset')
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')
opt = parser.parse_args()
last = get_latest_run() if opt.resume == 'get_last' else opt.resume # resume from most recent run
if last and not opt.weights:
print(f'Resuming training from {last}')
opt.weights = last if opt.resume and not opt.weights else opt.weights
if opt.local_rank in [-1, 0]:
check_git_status()
opt.cfg = check_file(opt.cfg) # check file
opt.data = check_file(opt.data) # check file
if opt.hyp: # update hyps
opt.hyp = check_file(opt.hyp) # check file
with open(opt.hyp) as f:
hyp.update(yaml.load(f, Loader=yaml.FullLoader)) # update hyps
opt.img_size.extend([opt.img_size[-1]] * (2 - len(opt.img_size))) # extend to 2 sizes (train, test)
device = torch_utils.select_device(opt.device, apex=mixed_precision, batch_size=opt.batch_size)
opt.total_batch_size = opt.batch_size
opt.world_size = 1
if device.type == 'cpu':
mixed_precision = False
elif opt.local_rank != -1:
# DDP mode
assert torch.cuda.device_count() > opt.local_rank
torch.cuda.set_device(opt.local_rank)
device = torch.device("cuda", opt.local_rank)
dist.init_process_group(backend='nccl', init_method='env://') # distributed backend
opt.world_size = dist.get_world_size()
assert opt.batch_size % opt.world_size == 0, "Batch size is not a multiple of the number of devices given!"
opt.batch_size = opt.total_batch_size // opt.world_size
print(opt)
# Train
if not opt.evolve:
if opt.local_rank in [-1, 0]:
print('Start Tensorboard with "tensorboard --logdir=runs", view at http://localhost:6006/')
tb_writer = SummaryWriter(log_dir=increment_dir('runs/exp', opt.name))
else:
tb_writer = None
train(hyp, tb_writer, opt, device)
# Evolve hyperparameters (optional)
else:
assert opt.local_rank == -1, "DDP mode currently not implemented for Evolve!"
tb_writer = None
opt.notest, opt.nosave = True, True # only test/save final epoch
if opt.bucket:
os.system('gsutil cp gs://%s/evolve.txt .' % opt.bucket) # download evolve.txt if exists
for _ in range(10): # generations to evolve
if os.path.exists('evolve.txt'): # if evolve.txt exists: select best hyps and mutate
# Select parent(s)
parent = 'single' # parent selection method: 'single' or 'weighted'
x = np.loadtxt('evolve.txt', ndmin=2)
n = min(5, len(x)) # number of previous results to consider
x = x[np.argsort(-fitness(x))][:n] # top n mutations
w = fitness(x) - fitness(x).min() # weights
if parent == 'single' or len(x) == 1:
# x = x[random.randint(0, n - 1)] # random selection
x = x[random.choices(range(n), weights=w)[0]] # weighted selection
elif parent == 'weighted':
x = (x * w.reshape(n, 1)).sum(0) / w.sum() # weighted combination
# Mutate
mp, s = 0.9, 0.2 # mutation probability, sigma
npr = np.random
npr.seed(int(time.time()))
g = np.array([1, 1, 1, 1, 1, 1, 1, 0, .1, 1, 0, 1, 1, 1, 1, 1, 1, 1]) # gains
ng = len(g)
v = np.ones(ng)
while all(v == 1): # mutate until a change occurs (prevent duplicates)
v = (g * (npr.random(ng) < mp) * npr.randn(ng) * npr.random() * s + 1).clip(0.3, 3.0)
for i, k in enumerate(hyp.keys()): # plt.hist(v.ravel(), 300)
hyp[k] = x[i + 7] * v[i] # mutate
# Clip to limits
keys = ['lr0', 'iou_t', 'momentum', 'weight_decay', 'hsv_s', 'hsv_v', 'translate', 'scale', 'fl_gamma']
limits = [(1e-5, 1e-2), (0.00, 0.70), (0.60, 0.98), (0, 0.001), (0, .9), (0, .9), (0, .9), (0, .9), (0, 3)]
for k, v in zip(keys, limits):
hyp[k] = np.clip(hyp[k], v[0], v[1])
# Train mutation
results = train(hyp.copy(), tb_writer, opt, device)
# Write mutation results
print_mutation(hyp, results, opt.bucket)
运行结果:


DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。
更多推荐

所有评论(0)