Sub topic 10
What the loss function trains: box, class and confidence terms
A detector learns from one number per training step: the loss. This chapter covers what that number is made of, how each part connects to the box, class and confidence outputs you decoded earlier, and which symptoms point to which part. It assumes you know what intersection over union (IoU) is, how a detector's raw outputs become boxes, and the basic idea of gradient descent.
Why a detector needs several loss terms
A classifier produces one label per image, so one cross-entropy term is enough. A detector produces many predictions per image, and each one must answer three questions:
- Is there an object here at all? (confidence, or objectness)
- If so, which class is it?
- Where exactly is it? (box coordinates)
Each question has a different kind of target. Presence is a yes/no value, class is a choice among several categories, and the box is a set of continuous numbers. Each kind needs its own loss function. The total loss is a weighted sum:
total_loss = w_box * box_loss + w_cls * cls_loss + w_obj * confidence_lossThe weights balance the terms. Without them, the term with the largest raw magnitude would dominate the gradients and the others would barely train.
The first step: deciding which prediction learns from which object
Before any term can be computed, the trainer must decide which predictions are responsible for which ground-truth objects. This step is called assignment.
A single-stage detector emits thousands of predictions per image, one for each grid cell or anchor point at each scale. Most of them land on background. Only a few should be trained to predict each real object.
- Older YOLO versions assign an object to the grid cell containing its centre, and to the anchor shape that best matches its size.
- Newer versions, including the YOLOv8 family, use a dynamic assigner. It scores every candidate by combining its class score and its IoU with the ground-truth box. It then picks the top few candidates inside the object as positives.
Everything not assigned is a negative. Negatives take part in the confidence or class loss, where they are pushed toward "nothing here". They are excluded from the box loss, because a background prediction has no correct box.
Assignment explains many training behaviours. For example, a very small object may receive few positive candidates, so it gets few gradient updates.
The box loss
The box loss measures how far a positive prediction is from its ground-truth box.
Why not plain coordinate error
You could use mean squared error on the four coordinates. This has two problems:
- Errors are not scale-aware. A 10-pixel error on a 20-pixel box is serious. The same error on a 500-pixel box is trivial, yet squared error treats them alike.
- It is not the metric you are judged on. Evaluation uses IoU, and the coordinate error and IoU do not move together.
Early YOLO versions reduced the first problem by predicting the square root of width and height. Modern versions instead optimise overlap directly.
IoU-based losses
The simplest overlap loss is:
loss_iou = 1 - IoU(pred, target)It is 0 for a perfect match and 1 when the boxes do not touch. It has a flaw: if the boxes do not overlap, IoU is 0 whatever the distance between them, so the gradient carries no information about which way to move.
The IoU family fixes this by adding penalty terms.
| Loss | Adds to `1 - IoU` | What it fixes |
|---|---|---|
| GIoU | Penalty based on the empty area of the smallest box enclosing both | Gives a gradient when boxes do not overlap |
| DIoU | Penalty on the distance between box centres | Faster convergence |
| CIoU | DIoU plus a penalty on aspect-ratio mismatch | Also pushes the width/height ratio toward the target |
YOLOv8 uses CIoU for the box term. It also adds a distribution focal loss (DFL). Rather than regressing each box edge as a single number, the model predicts a probability distribution over discrete offsets, and DFL trains that distribution to peak near the true edge. You do not need to implement it. Its practical effect is better localisation on boxes with ambiguous edges, such as blurred or occluded objects.
A small CIoU-style check
The following function computes 1 - IoU and a GIoU loss for corner-format boxes. It is a teaching sketch and not the Ultralytics implementation.
def iou_and_giou_loss(a, b):
# Boxes are (x1, y1, x2, y2).
ax1, ay1, ax2, ay2 = a
bx1, by1, bx2, by2 = b
inter = max(0, min(ax2, bx2) - max(ax1, bx1)) * max(0, min(ay2, by2) - max(ay1, by1))
area_a = (ax2 - ax1) * (ay2 - ay1)
area_b = (bx2 - bx1) * (by2 - by1)
union = area_a + area_b - inter
iou = inter / union if union > 0 else 0.0
# Smallest box enclosing both boxes.
cx1, cy1 = min(ax1, bx1), min(ay1, by1)
cx2, cy2 = max(ax2, bx2), max(ay2, by2)
enclose = (cx2 - cx1) * (cy2 - cy1)
giou = iou - (enclose - union) / enclose
return 1 - iou, 1 - giou
# Overlapping boxes: both losses are below the maximum.
print(iou_and_giou_loss((0, 0, 10, 10), (5, 5, 15, 15)))
# Disjoint boxes: 1 - IoU is stuck at 1.0, but GIoU still differs by distance.
print(iou_and_giou_loss((0, 0, 10, 10), (20, 20, 30, 30)))
print(iou_and_giou_loss((0, 0, 10, 10), (12, 0, 22, 10)))In the last two lines, 1 - IoU is 1.0 in both cases. The GIoU loss is larger for the farther pair, so it still tells the optimiser to move the box closer.
The class loss
The class term trains the model to name the object correctly.
- Classes are usually treated as independent yes/no decisions, using binary cross-entropy (BCE) on each class score after a sigmoid. This differs from the softmax used in plain classification. Independent scores allow overlapping labels and avoid forcing the scores to compete.
- In YOLOv8 the class target for a positive is not a hard 1. It is scaled by how well the predicted box matches the ground truth (its IoU). The model therefore learns that a high class score should go together with a well-placed box. This makes the score more useful for ranking boxes during non-maximum suppression.
- Some losses use focal weighting, which reduces the contribution of easy examples so that hard ones get more gradient. Variants of this appear across the YOLO family.
The confidence loss
In YOLOv5 and earlier, a separate objectness score says whether any object is present, and a BCE loss trains it. The target for positives is often the IoU between the predicted and true box, so confidence also reflects localisation quality. Negatives get a target of 0.
The imbalance problem is central here. A typical image has a handful of objects and thousands of background predictions. If every negative counted equally, the loss would be dominated by "nothing here" and the model could reach low loss by predicting nothing. Detectors handle this through:
- loss weights that lower the contribution of negatives,
- focal-style weighting that suppresses easy negatives,
- or assignment rules that limit how many negatives matter.
YOLOv8 removed the separate objectness branch. The class score alone carries both "is there an object" and "which class". This simplifies the head, but the idea remains: background predictions are trained toward low class scores.
How the terms interact
The diagram shows one training step.
The terms also compete, since they share the same backbone and neck. Heavy box-loss weight can improve localisation at some cost to classification, and the reverse is true as well. The default weights in Ultralytics were tuned on large benchmarks, so they are a sensible starting point for most custom datasets.
Reading the loss during training
Ultralytics logs box_loss, cls_loss and dfl_loss for training and validation every epoch. Watching them separately is more informative than watching the sum.
| Pattern | Likely cause | What to check |
|---|---|---|
| `box_loss` high, `cls_loss` low | Classes are easy, localisation is hard | Label box accuracy, image size, small objects |
| `cls_loss` high, `box_loss` low | Boxes are good, classes are confused | Similar classes, label mistakes, class imbalance |
| Training loss falls, validation loss rises | Overfitting | More data, augmentation, fewer epochs |
| All losses stay flat | Not learning | Learning rate, wrong label format, classes mapped incorrectly |
| Sudden spike to `nan` | Numerical instability | Learning rate too high, corrupt labels with zero-size boxes |
To change the balance, the training call accepts the gain parameters directly:
from ultralytics import YOLO
model = YOLO("yolov8n.pt")
# box, cls and dfl are the weights on the three loss terms.
model.train(data="my_data.yaml", epochs=50, imgsz=640, box=7.5, cls=0.5, dfl=1.5)The values shown are the usual defaults for this model family. Treat them as a baseline and change one at a time, comparing validation mAP, not the loss number alone.
Edge cases and pitfalls
- Loss values are not comparable across settings. Changing weights, image size or model version changes the scale of the loss. Compare runs by validation mAP.
- Low loss does not mean good detections. The loss is computed before non-maximum suppression and without a confidence threshold. A model can have a low loss and still produce poor results at your chosen thresholds.
- Bad labels pass straight into the loss. A box with zero width, a wrong class index or coordinates outside 0 to 1 gives a misleading target. Validate your label files before training.
- Missing labels teach the model that real objects are background. If an object is present but unlabelled, it becomes a negative. Consistent labelling matters more than a perfect loss weight.
- Small objects are under-trained. They get few positive assignments and small IoU changes for tiny pixel shifts. Higher
imgszor tiling often helps more than changing weights.
Exercise
A detector's validation cls_loss is low and falling, but box_loss stays high and mAP at IoU 0.5 to 0.95 is much lower than mAP at IoU 0.5. What does this suggest, and what are two things you would check or change?
Show answer
The model finds and names objects correctly, but its boxes are imprecise. mAP at IoU 0.5 only needs rough overlap, while mAP over 0.5 to 0.95 rewards tight boxes. Check the accuracy of the ground-truth boxes, since loose labels teach loose boxes. Then try a larger imgsz, especially if objects are small, or train longer. Raising the box gain is a further option, compared by validation mAP.
Exercise
Two boxes do not overlap, so their IoU is 0. Why does 1 - IoU fail as a loss in this case, and which loss from this chapter fixes it?
Show answer
The loss is constant at 1 whatever the distance between the boxes, so its gradient gives no direction in which to move the prediction. GIoU adds a penalty based on the empty area of the smallest enclosing box, which shrinks as the boxes move closer. DIoU and CIoU also fix this through a centre-distance penalty.