Meet YOLO26: next-gen vision AI.

YOLOv5のハイパーパラメータ進化

📚 This guide explains hyperparameter evolution for YOLOv5 🚀. Hyperparameter evolution is a method of Hyperparameter Optimization using a Genetic Algorithm (GA) for optimization.

機械学習におけるハイパーパラメータは、学習の様々な側面を制御するものであり、その最適値を見つけることは困難を伴う場合があります。グリッドサーチのような従来の手法では、以下のような理由からすぐに実行が困難になる可能性があります。

  1. 高次元な探索空間
  2. 各次元間の未知の相関関係
  3. 各点における適合度(fitness)評価のコストが高いこと

このため、遺伝的アルゴリズムはハイパーパラメータ探索に適した手法となります。

始める前に

Clone repo and install requirements.txt in a Python>=3.8.0 environment, including PyTorch>=1.8. Models and datasets download automatically from the latest YOLOv5 release.

git clone https://github.com/ultralytics/yolov5 # clone
cd yolov5
pip install -r requirements.txt # install

ハイパーパラメータの初期化

YOLOv5 has about 30 hyperparameters used for various training settings. These are defined in *.yaml files in the /data/hyps directory. Better initial guesses will produce better final results, so it is important to initialize these values properly before evolving. If in doubt, simply use the default values, which are optimized for YOLOv5 COCO training from scratch.

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

進化

Evolution is performed about a base scenario which we seek to improve upon. The base scenario in this example is fine-tuning COCO128 for 10 epochs using pretrained YOLOv5s. The base scenario training command is:

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/hyp_evolved.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/hyp_evolved.yaml --data your.yaml --weights yolov5s.pt

可視化する

evolve.csv is plotted as evolve.png by utils.plots.plot_evolve() after evolution finishes with one subplot per hyperparameter showing fitness (y-axis) vs hyperparameter values (x-axis). Yellow indicates higher concentrations. Vertical distributions indicate that a parameter has been disabled and does not mutate. This is user selectable in the meta dictionary in train.py, and is useful for fixing parameters and preventing them from evolving.

YOLOv5 ハイパーパラメータ進化の適合度結果

サポートされている環境

Ultralyticsは、プロジェクトを迅速に開始できるよう、CUDACUDNNPythonPyTorch といった必須の依存関係がプリインストールされた、すぐに使える環境を幅広く提供しています。

プロジェクトステータス

YOLOv5 CI

このバッジは、すべてのYOLOv5 GitHub Actions継続的インテグレーション(CI)テストが正常に通過していることを示しています。これらのCIテストは、学習検証推論エクスポート、およびベンチマークといったYOLOv5のさまざまな主要な側面について、機能とパフォーマンスを厳密にチェックします。macOS、Windows、Ubuntuにおいて一貫した信頼性の高い動作を保証しており、テストは24時間ごとおよび新しいコミットごとに実施されます。

コメント