Sub topic 11
Fine-tuning a Detector on Your Own Data
This chapter assumes you can run a pretrained YOLO model, you know the YOLO label format and data.yaml layout from the dataset chapter, and you understand the box, class and confidence loss terms. Here you will train on your own data, watch the run, and decide what to change when results disappoint.
Why fine-tune instead of training from scratch
A pretrained detector has already learned edges, textures, shapes and common object parts from a large dataset such as COCO. Fine-tuning starts from those weights and adjusts them to your classes. This usually gives better accuracy from far fewer labeled images, and training converges in fewer epochs.
Training from scratch makes sense only when your images look nothing like natural photos (for example, some medical or microscopy images) and you have a large labeled set. For most projects, start from a pretrained checkpoint.
When your classes differ from the pretrained ones, the final prediction layers get re-created with your class count. The backbone and neck weights are reused. The trainer reports this when it loads the weights.
The minimal training run
The dataset file from the previous chapter maps your folders and class names.
path: datasets/my_data
train: images/train
val: images/val
names:
0: cat
1: dogSave it as my_data.yaml. Then train and evaluate:
from ultralytics import YOLO
model = YOLO("yolov8n.pt")
model.train(data="my_data.yaml", epochs=50, imgsz=640)
metrics = model.val()
print("mAP50:", metrics.box.map50)
print("mAP50-95:", metrics.box.map)yolov8n.pt is the smallest model. Loading a .pt file gives you pretrained weights. Loading a .yaml model definition such as yolov8n.yaml builds the same architecture with random weights, which is training from scratch.
After training, the best checkpoint is saved under runs/detect/train/weights/best.pt. The trainer also writes last.pt, the state after the final epoch. Later runs use train2, train3 and so on unless you set name=.
The training loop at a glance
Each epoch is one pass over the training images. After every epoch the trainer runs validation, computes mAP, and keeps the checkpoint with the best fitness score. Fitness is mainly a weighted blend of mAP50 and mAP50-95, with most weight on mAP50-95.
Hyperparameters that matter first
Ultralytics has many settings. These few cover most real projects.
| Argument | What it controls | Practical guidance |
|---|---|---|
| `epochs` | Passes over the training set | 50 to 100 for small datasets. More if validation mAP is still rising. |
| `imgsz` | Input size in pixels (square) | 640 is the default. Raise it when objects are small, at the cost of memory and speed. |
| `batch` | Images per update | Largest that fits in GPU memory. `-1` picks automatically on a single GPU. |
| `patience` | Epochs without improvement before early stop | Default is 100. Lower values such as 20 save time. |
| `freeze` | Number of leading layers to hold fixed | Useful for tiny datasets. Try `freeze=10` to freeze the backbone. |
| `lr0` | Initial learning rate | Leave the default unless training is unstable. |
| `device` | Which GPU or CPU | `device=0` for the first GPU, `device="cpu"` otherwise. |
A run with more control looks like this:
from ultralytics import YOLO
model = YOLO("yolov8s.pt")
model.train(
data="my_data.yaml",
epochs=100,
imgsz=640,
batch=16,
patience=20,
freeze=10,
device=0,
name="cats_dogs_s",
)Model size
The letters in the model name (n, s, m, l, x) mark size. Larger models are more accurate and slower, with more memory use. With a few hundred images, a small model such as n or s is often enough. A large model on a tiny dataset tends to overfit without gaining accuracy.
Freezing layers
Freezing the backbone keeps the pretrained features fixed and trains only the later layers. This reduces overfitting when you have very few images and trains faster. The cost is lower ceiling accuracy when your domain differs from the pretraining data. A common approach is to train frozen first, then train again unfrozen from that result with a lower learning rate if you need more accuracy.
Augmentation
During training, each image is randomly altered so the model sees varied versions. Ultralytics enables several by default:
- HSV color shifts, which vary hue, saturation and brightness.
- Horizontal flips (
fliplr=0.5). - Scaling and translation.
- Mosaic, which stitches four images into one training image so objects appear at different scales and contexts.
Defaults suit general photos. Change them when they conflict with your data. If left and right matter (for example, reading text or distinguishing a left from a right hand), set fliplr=0.0. If your camera is fixed and lighting never changes, color shifts add little.
The trainer turns mosaic off for the last epochs (close_mosaic=10 by default). This lets the model finish on images that look like real, uncut scenes.
Reading the training output
Each epoch prints box loss, class loss and a distribution focal loss term for box edges, followed by validation precision, recall, mAP50 and mAP50-95. Ultralytics also saves results.csv and plots in the run folder, including results.png, a confusion matrix, and sample batches.
Check these in order:
- Sample batches (
train_batch0.jpg). Boxes drawn on the images must sit on the objects. If they are shifted or the wrong size, your labels or coordinates are wrong, and no setting will fix that. - Loss curves. Training losses should fall steadily.
- Validation mAP. It should rise and then flatten.
- Confusion matrix. It shows which classes are confused with each other or with background.
Recognizing overfitting and underfitting
The patterns below describe what the curves tell you.
| Pattern | Likely cause | What to try |
|---|---|---|
| Training loss falls, validation mAP stalls or drops | Overfitting | More data, stronger augmentation, smaller model, `freeze`, fewer epochs |
| Both training loss and validation mAP stay poor | Underfitting or label problems | Check labels, train longer, larger model, larger `imgsz` |
| Validation mAP very high from epoch 1 | Possible leakage between train and val | Make sure the same scene or near-duplicate frames are not in both splits |
| Loss becomes `nan` | Unstable training | Lower `lr0`, check for corrupt labels, try smaller `batch` |
Data leakage deserves attention for video. Frames from the same clip look almost identical, so a random split puts near-copies in both train and val, and mAP looks better than it will be on new footage. Split by clip or by scene instead.
Resuming and continuing
If a run stops, resume it from its last checkpoint:
from ultralytics import YOLO
model = YOLO("runs/detect/train/weights/last.pt")
model.train(resume=True)To start a new run from your own earlier result, for example to add data, load best.pt and call train with a new data file and a smaller learning rate. That is a new run that begins from your weights, not a resume.
Common mistakes
- Wrong class order. The index in each label file must match the
namesmapping. Swapping them trains without error and gives wrong class names. - Unnormalized coordinates. Label values must be between 0 and 1. Pixel values cause the trainer to flag the labels as corrupt and skip those images.
- Images and labels not paired. The trainer finds labels by replacing
imageswithlabelsin the path. A mismatched folder name gives "no labels found" warnings and a model that learns nothing. - Reading the first epochs too literally. mAP is low early in training while the new head adapts. Judge the curve after it flattens.
- Cached labels. The trainer writes a
labels.cachefile next to the labels. If you edit labels and results do not change, delete the cache file so it is rebuilt. - Too few examples of a class. A class with a handful of boxes will have unstable AP. Count instances per class before training.
Checking the result on real images
Numbers can hide problems, so look at predictions too:
from ultralytics import YOLO
model = YOLO("runs/detect/train/weights/best.pt")
results = model.predict("datasets/my_data/images/val", conf=0.25, save=True)
print(len(results), "images processed")The annotated images are saved in a runs/detect/predict folder. Look for missed objects, duplicate boxes, and confident wrong classes, and compare them with the confusion matrix. The next chapters on evaluation and thresholds explain how to measure and tune what you find.
Exercise
You fine-tune a detector on 300 images extracted from 6 video clips, splitting frames randomly 80/20 into train and val. Validation mAP50-95 is 0.92 after a few epochs, but on a new clip the detector misses many objects. What is the most likely cause, and what two changes would you make?
Show answer
The random frame split leaked near-identical frames from the same clips into both train and val, so validation mAP was inflated. Re-split by clip, so each clip is entirely in train or entirely in val, and add more varied footage (more clips, different lighting and angles). You can also use a smaller model or freeze to reduce overfitting to the few clips you have.
Exercise
Your run shows training box loss falling every epoch, but validation mAP50-95 peaked at epoch 30 of 100 and has slowly dropped since. Which file do you deploy, and which settings would you change to avoid wasting time next run?
Show answer
Deploy best.pt, which was saved at the epoch with the best fitness (around epoch 30), not last.pt. For the next run, lower patience (for example 15 to 20) so training stops early, and consider fewer epochs, stronger augmentation, a smaller model or freeze to reduce overfitting.