Sub topic 3
What the loss function trains: box, class and confidence terms
This chapter assumes you know Python, can install the ultralytics package, and understand IoU and non-maximum suppression (NMS) from the earlier chapters.
What the loss function trains
A YOLO detector is trained by a loss function that adds three terms. The box term pulls predicted boxes toward labeled boxes. The class term teaches the correct label. The confidence term teaches the model to score cells that contain an object high and empty cells low.
Fine-tuning a detector on your own data
Start from pretrained weights and point the trainer at a dataset YAML file in YOLO format.
from ultralytics import YOLO
model = YOLO("yolov8n.pt")
model.train(data="my_data.yaml", epochs=50, imgsz=640)Evaluating a detector with precision, recall and mAP
Precision is the share of predicted boxes that are correct. Recall is the share of real objects the model finds. Average precision (AP) is the area under the precision-recall curve for one class. Mean average precision (mAP) averages AP across classes. mAP50 counts a match at IoU 0.5. mAP50-95 averages IoU from 0.5 to 0.95, which is stricter.
Choosing confidence and IoU thresholds
The confidence threshold drops weak detections. Raising it reduces false positives. Lowering it finds more objects. The NMS IoU threshold sets how much overlap counts as a duplicate. Tune both on validation data.
Exporting a trained model for deployment
Export the best checkpoint, which the trainer selects by validation mAP.
from ultralytics import YOLO
model = YOLO("runs/detect/train/weights/best.pt")
model.export(format="onnx")Diagnosing poor detections
| Symptom | Likely cause | Fix |
|---|---|---|
| Many false positives | Confidence threshold too low | Raise the confidence threshold or add negative images |
| Missed objects | Threshold too high or too few examples | Lower the threshold or label more examples |
| Boxes off target | Label errors or wrong coordinate format | Check label files and normalized coordinates |
The YOLO family: how versions differ
Newer YOLO versions change the backbone, neck and head, along with the training recipe. Model sizes such as n, s, m and l trade speed for accuracy. Check the release notes for your version, because weight files and APIs differ between versions.
Exercise
Your model has high recall but low precision. Which threshold do you raise first, and why?
Show answer
Raise the confidence threshold. It removes weak detections, which make up most of the false positives, and leaves the strong detections in place.