Sub topic 11
Fine-Tuning a Detector on Your Own Data
This chapter assumes you know basic Python, image arrays, neural-network training, and the YOLO inference workflow. You will fine-tune a pretrained YOLO detector so it recognizes classes from your own labeled images.
Organize the dataset
Fine-tuning starts with labeled examples. Each image needs a matching text file. Each line in that file describes one object:
# labels/train/img001.txt
# class_id x_center y_center width height
0 0.512 0.430 0.200 0.350
1 0.150 0.700 0.100 0.220The coordinates are normalized to the range 0 to 1. The box uses its center, width, and height, unlike the pixel-based (x1, y1, x2, y2) format used during inference.
A typical directory layout separates training and validation images:
datasets/my_data/
├── images/
│ ├── train/
│ └── val/
└── labels/
├── train/
└── val/Every image should have a label file with the same base name. An image with no objects should have an empty label file, not a missing file.
Create a YAML configuration file that connects the images to their class names:
path: datasets/my_data
train: images/train
val: images/val
names:
0: cat
1: dogThe class index is part of the contract. If 0 means cat during labeling, it must mean cat in this file.
Start from pretrained weights
A pretrained model has already learned general visual features such as edges, textures, and shapes. Fine-tuning adjusts those weights for your classes. This usually needs less data and time than training from random weights.
from ultralytics import YOLO
model = YOLO("yolov8n.pt")
model.train(
data="my_data.yaml",
epochs=50,
imgsz=640,
batch=16,
patience=10,
)
metrics = model.val()
print("mAP50:", metrics.box.map50)
print("mAP50-95:", metrics.box.map)The epochs value controls how many passes the trainer makes over the training set. imgsz resizes inputs to a common image size. Larger images can help with small objects but require more memory. patience stops training when validation performance stops improving.
The trainer uses several loss terms. Box loss measures localization error, classification loss measures wrong class predictions, and objectness or confidence loss measures whether a predicted region contains an object. The combined loss drives gradient updates to the model.
Check the result
Use the validation split only for measurement, not for repeated manual tuning. Compare metrics with actual predictions. A high score can hide failures on small objects, crowded scenes, or unusual lighting. Review false positives and missed objects separately.
Exercise
Your labels use class index 1 for cats, but the YAML file assigns index 1 to dogs. What is the likely result?
Show answer
The detector learns the wrong class name for those examples. Make the label indices and YAML names agree, then retrain.