YOLOv5 的超参数进化#
📚 本指南解释了 YOLOv5 的超参数进化 🚀。超参数进化是一种使用遗传算法(GA)进行优化的超参数优化方法。
机器学习中的超参数控制着训练的各个方面,为它们找到最佳值可能是一个挑战。诸如网格搜索之类的传统方法由于以下原因很快就会变得难以处理:
- 高维搜索空间
- 维度之间未知的相关性
- 在每个点评估适应度的成本高昂
这使得遗传算法成为超参数搜索的合适候选方案。
开始之前#
克隆仓库并在包含 PyTorch>=1.8 的 Python>=3.8.0 环境中安装 requirements.txt。模型和数据集会从最新的 YOLOv5 发布版本中自动下载。
git clone https://github.com/ultralytics/yolov5 # clone
cd yolov5
pip install -r requirements.txt # install初始化超参数#
YOLOv5 大约有 30 个用于各种训练设置的超参数。它们定义在 /data/hyps 目录中的 *.yaml 文件里。更好的初始猜测会产生更好的最终结果,因此在进化之前正确初始化这些值非常重要。如有疑问,直接使用默认值即可,这些默认值针对 YOLOv5 从头开始训练 COCO 进行了优化。
# YOLOv5 🚀 by Ultralytics, AGPL-3.0 license
# Hyperparameters for low-augmentation COCO training from scratch
# python train.py --batch 64 --cfg yolov5n6.yaml --weights '' --data coco.yaml --img 640 --epochs 300 --linear
# See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials
lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3)
lrf: 0.01 # final OneCycleLR learning rate (lr0 * lrf)
momentum: 0.937 # SGD momentum/Adam beta1
weight_decay: 0.0005 # optimizer weight decay 5e-4
warmup_epochs: 3.0 # warmup epochs (fractions ok)
warmup_momentum: 0.8 # warmup initial momentum
warmup_bias_lr: 0.1 # warmup initial bias lr
box: 0.05 # box loss gain
cls: 0.5 # cls loss gain
cls_pw: 1.0 # cls BCELoss positive_weight
obj: 1.0 # obj loss gain (scale with pixels)
obj_pw: 1.0 # obj BCELoss positive_weight
iou_t: 0.20 # IoU training threshold
anchor_t: 4.0 # anchor-multiple threshold
# anchors: 3 # anchors per output layer (0 to ignore)
fl_gamma: 0.0 # focal loss gamma (efficientDet default 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.1 # image translation (+/- fraction)
scale: 0.5 # image scale (+/- gain)
shear: 0.0 # image shear (+/- deg)
perspective: 0.0 # image perspective (+/- fraction), range 0-0.001
flipud: 0.0 # image flip up-down (probability)
fliplr: 0.5 # image flip left-right (probability)
mosaic: 1.0 # image mosaic (probability)
mixup: 0.0 # image mixup (probability)
copy_paste: 0.0 # segment copy-paste (probability)定义适应度#
适应度(Fitness)是我们力求最大化的值。在 YOLOv5 中,我们将默认的适应度函数定义为指标的加权组合:mAP@0.5 贡献 10% 的权重,mAP@0.5:0.95 贡献剩余的 90%,其中不包含准确率 (P) 和召回率 (R)。你可以根据需要进行调整,或者使用 utils/metrics.py 中的默认适应度定义(推荐)。
def fitness(x):
"""Return model fitness as the sum of weighted metrics [P, R, mAP@0.5, mAP@0.5:0.95]."""
w = [0.0, 0.0, 0.1, 0.9] # weights for [P, R, mAP@0.5, mAP@0.5:0.95]
return (x[:, :4] * w).sum(1)进化#
进化是围绕我们试图改进的基础场景进行的。本例中的基础场景是使用预训练的 YOLOv5s 对 COCO128 进行 10 个轮次的微调。基础场景的训练命令是:
python train.py --epochs 10 --data coco128.yaml --weights yolov5s.pt --cache要演化特定于此场景的超参数,从我们在第 1 节中定义的初始值开始,并使在第 2 节中定义的适应度最大化,请附加 --evolve:
# Single-GPU
python train.py --epochs 10 --data coco128.yaml --weights yolov5s.pt --cache --evolve
# Multi-GPU with delay
for i in {0..7}; do
sleep $((30 * i)) # 30-second delay (optional)
echo "Starting GPU $i..."
nohup python train.py --epochs 10 --data coco128.yaml --weights yolov5s.pt --cache --device $i --evolve > "evolve_gpu_$i.log" &
done
# Continuous training (use with caution)
# for i in {0..7}; do
# sleep $((30 * i)) # 30-second delay (optional)
# echo "Starting continuous training on GPU $i..."
# (
# while true; do
# python train.py --epochs 10 --data coco128.yaml --weights yolov5s.pt --cache --device $i --evolve > "evolve_gpu_$i.log"
# done
# ) &
# done默认的演化设置将运行基础场景 300 次,即进行 300 代。你可以通过 --evolve 参数修改代数,即 python train.py --evolve 1000。
主要的遗传算子是交叉和变异。在这项工作中使用了变异,具有 80% 的概率和 0.04 的方差,以便基于所有先前世代中最佳父代的组合来创建新的后代。结果会记录到 runs/evolve/exp/evolve.csv 中,并且每个世代都会保存适应度最高的后代作为 runs/evolve/exp/hyp_evolve.yaml:
# YOLOv5 Hyperparameter Evolution Results
# Best generation: 287
# Last generation: 300
# metrics/precision, metrics/recall, metrics/mAP_0.5, metrics/mAP_0.5:0.95, val/box_loss, val/obj_loss, val/cls_loss
# 0.54634, 0.55625, 0.58201, 0.33665, 0.056451, 0.042892, 0.013441
lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3)
lrf: 0.2 # final OneCycleLR learning rate (lr0 * lrf)
momentum: 0.937 # SGD momentum/Adam beta1
weight_decay: 0.0005 # optimizer weight decay 5e-4
warmup_epochs: 3.0 # warmup epochs (fractions ok)
warmup_momentum: 0.8 # warmup initial momentum
warmup_bias_lr: 0.1 # warmup initial bias lr
box: 0.05 # box loss gain
cls: 0.5 # cls loss gain
cls_pw: 1.0 # cls BCELoss positive_weight
obj: 1.0 # obj loss gain (scale with pixels)
obj_pw: 1.0 # obj BCELoss positive_weight
iou_t: 0.20 # IoU training threshold
anchor_t: 4.0 # anchor-multiple threshold
# anchors: 3 # anchors per output layer (0 to ignore)
fl_gamma: 0.0 # focal loss gamma (efficientDet default 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.1 # image translation (+/- fraction)
scale: 0.5 # image scale (+/- gain)
shear: 0.0 # image shear (+/- deg)
perspective: 0.0 # image perspective (+/- fraction), range 0-0.001
flipud: 0.0 # image flip up-down (probability)
fliplr: 0.5 # image flip left-right (probability)
mosaic: 1.0 # image mosaic (probability)
mixup: 0.0 # image mixup (probability)
copy_paste: 0.0 # segment copy-paste (probability)我们建议至少进行 300 代进化以获得最佳结果。请注意,进化通常既昂贵又耗时,因为基准场景会被训练数百次,可能需要数百或数千个 GPU 小时。
当演化结束时,通过将训练指向保存的文件来重新使用发现的设置,例如 python train.py --hyp runs/evolve/exp/hyp_evolve.yaml --data your.yaml --weights yolov5s.pt。
可视化#
utils.plots.plot_evolve() 在进化结束后将 evolve.csv 绘制为 evolve.png,每个超参数对应一个子图,显示适应度(y 轴)对超参数值(x 轴)。黄色表示较高的浓度。垂直分布表明某个参数已被禁用且不发生突变。这可以在 train.py 的 meta 字典中由用户选择,对于固定参数和防止它们进化非常有用。

支持的环境#
Ultralytics 提供了各种开箱即用的环境,每个环境都预先安装了诸如 CUDA、CUDNN、Python 和 PyTorch 等基本依赖项,以帮助你快速启动项目。
- 免费 GPU 笔记本:
- Google Cloud:GCP 快速入门指南
- Amazon:AWS 快速入门指南
- Azure:AzureML 快速入门指南
- Docker:Docker 快速入门指南
项目状态#
此徽章表示所有 YOLOv5 GitHub Actions 持续集成 (CI) 测试均已成功通过。这些 CI 测试严格检查了 YOLOv5 在各个核心方面的功能和性能:训练、验证、推理、导出和基准测试。它们确保在 macOS、Windows 和 Ubuntu 上保持一致且可靠的运行,测试每 24 小时以及每次新提交时进行。