Link to this sectionYOLOv5 하이퍼파라미터 진화#
📚 This guide explains hyperparameter evolution for YOLOv5 🚀. Hyperparameter evolution is a method of Hyperparameter Optimization using a Genetic Algorithm (GA) for optimization.
머신 러닝의 하이퍼파라미터는 학습의 다양한 측면을 제어하며, 최적의 값을 찾는 것은 어려운 과제가 될 수 있습니다. 그리드 서치(grid search)와 같은 기존 방식은 다음과 같은 이유로 빠르게 실행 불가능해질 수 있습니다:
- 고차원 검색 공간
- 차원 간의 알려지지 않은 상관관계
- 각 지점에서의 적합도(fitness) 평가 비용이 높음
이러한 이유로 유전 알고리즘이 하이퍼파라미터 검색을 위한 적합한 후보가 됩니다.
Link to this section시작하기 전에#
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 # installLink to this section1. 하이퍼파라미터 초기화#
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)Link to this section2. 적합도(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)Link to this section3. 진화(Evolve)#
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).
주요 유전 연산자는 **교차(crossover)**와 **돌연변이(mutation)**입니다. 이 작업에서는 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.
Link to this section시각화#
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.

Link to this section지원되는 환경#
Ultralytics는 프로젝트를 신속하게 시작할 수 있도록 CUDA, CUDNN, Python, PyTorch와 같은 필수 종속성이 미리 설치된 다양한 환경을 제공합니다.
- 무료 GPU 노트북:
- Google Cloud: GCP 퀵스타트 가이드
- Amazon: AWS 퀵스타트 가이드
- Azure: AzureML 퀵스타트 가이드
- Docker: Docker 퀵스타트 가이드
Link to this section프로젝트 상태#
이 배지는 모든 YOLOv5 GitHub Actions 지속적 통합(CI) 테스트가 성공적으로 통과했음을 나타냅니다. 이러한 CI 테스트는 학습, 검증, 추론, 내보내기 및 벤치마크와 같은 YOLOv5의 다양한 핵심 측면에 걸쳐 기능과 성능을 엄격하게 점검합니다. 이는 24시간마다 그리고 새로운 커밋이 발생할 때마다 테스트를 수행하여 macOS, Windows 및 Ubuntu에서 일관되고 안정적인 운영을 보장합니다.