Sub topic 15
Diagnosing poor detections
This chapter assumes you can run a pretrained YOLO model, read its boxes and scores, train on a YOLO-format dataset, and interpret precision, recall and mAP. You also need to know how confidence and NMS IoU thresholds change the output. Here you learn to turn a bad result into a specific cause, then apply the fix that targets it.
Start with symptoms, not guesses
A detector that "doesn't work" usually fails in one of a few ways. Name the symptom first, because each symptom points to different causes.
| Symptom | Metric signature | Likely causes |
|---|---|---|
| Objects are missed | Low recall | Confidence threshold too high, small objects, too little data, missing labels |
| Many false boxes | Low precision | Confidence threshold too low, background confusion, label noise |
| Duplicate boxes on one object | Precision drops at low NMS IoU thresholds | NMS IoU threshold too high, or crowded scenes handled badly |
| Real neighbours merged into one box | Recall drops in crowds | NMS IoU threshold too low |
| Right object, wrong label | Off-diagonal confusion matrix cells | Similar classes, inconsistent labels |
| Boxes loosely fit | mAP50 fine, mAP50-95 poor | Imprecise labels, low input resolution, undertrained box regression |
| Good on validation, bad in production | Large gap between validation and real use | Domain shift, leakage between splits |
A diagnostic workflow
Work from cheap checks to expensive ones. Most problems are found in the first two steps.
Step 1: verify the pipeline
Many "model" problems are data problems. Check these before changing any hyperparameter:
- The
namesmapping in the dataset YAML matches the class indices in the label files. An off-by-one shift gives confident but wrongly named boxes. - Label coordinates are normalized to 0-1 and use centre format (
x_center y_center width height). Pixel values or corner coordinates produce boxes far outside the image, which the trainer may silently drop. - Each label file has the same base name as its image, and the
imagesandlabelsfolders mirror each other. - Training and validation images do not overlap. Near-duplicate frames from one video split across both sets inflate validation scores.
The trainer reports corrupt or ignored labels in its log at startup. Read that log; warnings about "ignoring corrupt image/label" tell you how much of your data is unused.
A script can catch the most common label errors before training:
from pathlib import Path
def check_labels(label_dir, num_classes):
problems = []
for path in Path(label_dir).glob("*.txt"):
for n, line in enumerate(path.read_text().splitlines(), 1):
parts = line.split()
if len(parts) != 5:
problems.append((path.name, n, "expected 5 fields"))
continue
cls = float(parts[0])
if cls != int(cls) or not 0 <= int(cls) < num_classes:
problems.append((path.name, n, f"bad class {parts[0]}"))
if any(not 0.0 <= float(v) <= 1.0 for v in parts[1:]):
problems.append((path.name, n, "coordinate outside 0-1"))
return problems
for problem in check_labels("datasets/my_data/labels/train", num_classes=2):
print(problem)Step 2: look at predictions on real images
Metrics summarize; images explain. Run the model on 20 to 50 validation images and plot the boxes. Then do the same with the ground truth labels drawn on the same images. Disagreements fall into patterns: a missing label the model correctly found, a box shifted consistently in one direction, a whole class never predicted. Ultralytics saves such images during training and validation, including a confusion matrix and prediction-versus-label grids in the run folder.
from ultralytics import YOLO
model = YOLO("runs/detect/train/weights/best.pt")
# Very low conf shows what the model "sees" before thresholding hides it.
results = model.predict("datasets/my_data/images/val", conf=0.05, save=True)
print(len(results), "images saved under runs/detect/")Predicting with a very low confidence threshold separates two cases. If the missed object appears at a score of 0.1, the model found it and your threshold hid it. If it never appears, the model did not learn it.
Failure modes in detail
Missed small objects
Detectors downsample the image through the backbone, so tiny objects occupy only a few cells in the final feature maps. An object that is 10 pixels wide at 640 input may be 1 pixel wide at the coarsest scale. Options, in rough order of cost:
- Raise
imgszfor training and inference (for example 960 or 1280). Compute and memory grow with the square of the size. - Use a larger model variant.
- Tile large images into overlapping crops, detect on each crop, and merge results with NMS.
- Check that the labels for small objects exist at all. Annotators often skip them.
False positives on background
If the model fires on shadows, textures or objects of other types, it has not seen enough negatives. Add images with no objects of interest. In YOLO format, a background image has an empty or absent label file. Also look at which false positives are really unlabelled true objects: if so, fix the labels rather than the model.
Confusion between similar classes
Open the confusion matrix. A bright off-diagonal cell between two classes means they look alike or were labelled inconsistently. Compare crops of both classes side by side. If a human cannot tell them apart from the crop, the labelling rule is the problem. If a human can, you need more examples of the harder class or higher resolution.
Class imbalance
When one class has ten times the examples of another, the rare class gets low recall. Collect more rare examples first. Oversampling by copying images or lowering the confidence threshold for that class are secondary measures.
Duplicates and merged boxes
NMS removes boxes that overlap a higher-scoring box by more than the IoU threshold. A threshold of 0.7 keeps more overlapping boxes, so duplicates can survive. A threshold of 0.3 is aggressive, so two people standing close together may become one detection. Tune it on validation data in the density your application sees.
Overfitting
Training loss keeps falling while validation mAP stalls or drops. Signs include perfect results on training images and poor results on new ones. Remedies: more varied data, stronger augmentation, fewer epochs, or stopping early. A small dataset with a large model overfits quickly.
Domain shift
The model was trained on daytime photos and is deployed on night video, or on a different camera, angle or resolution. Validation mAP is high because validation resembles training. The fix is data from the deployment domain. Build a small test set from real production frames and score the model on it separately from the main validation set.
Loose boxes
If mAP50 is acceptable but mAP50-95 is low, the model finds objects but localizes them imprecisely. Check label quality first: boxes drawn with margins teach the model to draw margins. Then train longer, or use a larger model.
Separating threshold problems from model problems
Before retraining, sweep the confidence threshold on the validation set and watch precision and recall change. Retraining is costly. A threshold change is free.
from ultralytics import YOLO
model = YOLO("runs/detect/train/weights/best.pt")
for conf in (0.1, 0.25, 0.5):
m = model.val(data="my_data.yaml", conf=conf, iou=0.6, plots=False)
print(f"conf={conf}: P={m.box.mp:.3f} R={m.box.mr:.3f} mAP50={m.box.map50:.3f}")Note that mp and mr are mean precision and recall across classes at the operating point the validator selects, so compare trends rather than treating the numbers as exact. Use a low conf when you compute mAP, because mAP integrates over the whole precision-recall curve and needs low-score detections. Use your chosen deployment conf for the precision and recall you report to users.
Common mistakes in diagnosis
- Changing several things at once. Alter one variable per experiment, or you will not know what helped.
- Judging by mAP alone. Two models with equal mAP can have very different precision and recall at your deployment threshold.
- Tuning on the test set. Keep a held-out set that you look at only for final reporting.
- Training longer to fix a data problem. More epochs on mislabelled data memorizes the errors.
- Ignoring inference preprocessing. Different image size, colour order (BGR versus RGB) or letterboxing between training and deployment degrades results with no error message.
Exercise
A fine-tuned detector shows mAP50 of 0.85 but mAP50-95 of 0.38. In a test, predicting at conf=0.05 shows that the objects are found, but the boxes look loose. List two checks or fixes in order, and explain why a higher confidence threshold would not help.
Show answer
First, inspect the labels: loose or margin-padded annotation boxes teach the model loose boxes, so retighten them. Second, train longer, increase image size or use a larger model so box regression improves. A higher confidence threshold only filters detections by score. It does not move box edges, so it cannot raise the high-IoU mAP that is limiting the score here.
Exercise
Two people standing shoulder to shoulder are reported as one box, while a single large dog is reported twice. Which NMS IoU threshold change addresses each problem, and what is the risk of overcorrecting?
Show answer
The merged people come from a threshold that is too low: raise it so that overlapping boxes of different objects survive. The doubled dog comes from a threshold that is too high: lower it so that the duplicate is suppressed. Overcorrecting in either direction trades one error for the other, so tune the threshold on validation images that match your real scene density.