YOLOv5 için Hiperparametre Evrimi

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

Makine öğrenimindeki hiperparametreler, eğitimin çeşitli yönlerini kontrol eder ve bunlar için en uygun değerleri bulmak zorlu bir iş olabilir. Izgara aramaları gibi geleneksel yöntemler, aşağıdakiler nedeniyle hızla içinden çıkılmaz bir hal alabilir:

  1. Yüksek boyutlu arama uzayı
  2. Boyutlar arasındaki bilinmeyen korelasyonlar
  3. Her noktadaki uygunluğun değerlendirilmesinin maliyetli olması

Bu durum, genetik algoritmaları hiperparametre aramaları için uygun bir aday haline getirir.

Başlamadan Önce

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

Hiperparametreleri Başlat

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)

Uygunluğu (Fitness) Tanımla

Uygunluk (Fitness), maksimize etmeye çalıştığımız değerdir. YOLOv5'te varsayılan uygunluk fonksiyonunu metriklerin ağırlıklı bir kombinasyonu olarak tanımlarız: mAP@0.5 ağırlığın %10'unu, mAP@0.5:0.95 ise geri kalan %90'ını oluşturur; hassasiyet (P) ve duyarlılık (R) ise dahil edilmez. Bunları uygun gördüğün şekilde ayarlayabilir veya utils/metrics.py içindeki varsayılan uygunluk tanımını kullanabilirsin (önerilir).

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)

Evrimleştir

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

Bölüm 1'de tanımlanan başlangıç değerlerimizden başlayarak ve Bölüm 2'de tanımlanan uygunluğu maksimize ederek, bu senaryoya özel hiperparametreleri evrimleştirmek için --evolve ekle:

# 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

Varsayılan evrim ayarları, temel senaryoyu 300 kez, yani 300 nesil boyunca çalıştıracaktır. Nesil sayısını --evolve argümanı aracılığıyla değiştirebilirsin, örneğin python train.py --evolve 1000.

Temel genetik operatörler çaprazlama (crossover) ve mutasyondur. Bu çalışmada, önceki tüm nesillerdeki en iyi ebeveynlerin kombinasyonuna dayalı yeni nesiller oluşturmak için %80 olasılık ve 0.04 varyans ile mutasyon kullanılır. Sonuçlar runs/evolve/exp/evolve.csv dosyasına kaydedilir ve en yüksek uygunluğa sahip nesil her nesilde runs/evolve/hyp_evolved.yaml olarak kaydedilir:

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

En iyi sonuçlar için en az 300 nesil evrim öneriyoruz. Temel senaryo yüzlerce kez eğitildiği için evrimin genellikle maliyetli ve zaman alıcı olduğunu, potansiyel olarak yüzlerce veya binlerce GPU saati gerektirebileceğini unutma.

Evrim bittiğinde, eğitim komutunda kaydedilen dosyayı göstererek keşfedilen ayarları yeniden kullanabilirsin; örneğin python train.py --hyp runs/evolve/hyp_evolved.yaml --data your.yaml --weights yolov5s.pt.

Görselleştir

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 hiperparametre evrimi uygunluk sonuçları

Desteklenen Ortamlar

Ultralytics, projelerine hızlı bir başlangıç yapman için CUDA, CUDNN, Python ve PyTorch gibi temel bağımlılıkların önceden yüklü olduğu, kullanıma hazır çeşitli ortamlar sunar.

Proje Durumu

YOLOv5 CI

Bu rozet, tüm YOLOv5 GitHub Actions Sürekli Entegrasyon (CI) testlerinin başarıyla geçtiğini gösterir. Bu CI testleri, YOLOv5'in işlevselliğini ve performansını çeşitli temel açılardan titizlikle kontrol eder: eğitim, doğrulama, çıkarım, dışa aktarma ve kıyaslamalar. macOS, Windows ve Ubuntu üzerinde tutarlı ve güvenilir bir çalışma sağlarlar; testler her 24 saatte bir ve her yeni commit'te gerçekleştirilir.

Yorumlar