Sub topic 8
Classification and Box Losses, and Focal Loss
This chapter assumes you know binary cross-entropy, how gradient descent uses a loss, and how anchors are matched to ground truth. The previous chapters covered anchors, box encoding, and positive/negative assignment. Here we turn those assignments into a training signal.
Two outputs, two losses
A detector predicts two things per anchor: a class score and box offsets. These are different problems, so they get different losses.
- Classification loss. For every anchor, it asks whether the class prediction matches the label (a class, or background).
- Box regression loss. It asks whether the predicted offsets match the encoded target offsets. It applies only to positive anchors, because a background anchor has no box to match.
The total is a weighted sum, normalized by the number of positive anchors so that images with many objects do not dominate:
L = (1 / N_pos) * (L_cls + lambda * L_box)
Box regression losses
The regression targets are the encoded offsets (tx, ty, tw, th) from the box-encoding chapter. A plain L2 loss is sensitive to outliers: an anchor with a large error produces a large gradient that can destabilize training. L1 has a constant gradient but is not smooth at zero. Smooth L1 (the Huber loss) combines them: quadratic for small errors, linear for large ones.
import numpy as np
def smooth_l1(x, beta=1.0):
ax = np.abs(x)
return np.where(ax < beta, 0.5 * ax ** 2 / beta, ax - 0.5 * beta)
errors = np.array([0.2, 3.0])
print(smooth_l1(errors).round(4).tolist()) # [0.02, 2.5]Two caveats apply:
- Smooth L1 is computed on each of the four offsets independently. A small loss on each coordinate does not guarantee a high IoU, and IoU is the metric you are judged on.
- Regressing offsets (not raw pixels) keeps the targets at a similar scale across object sizes. Some detectors still divide the offsets by fixed constants to equalize their variances.
IoU-based losses address the mismatch directly. 1 - IoU is computed on decoded boxes. It fails when boxes do not overlap, since IoU is 0 and the gradient vanishes. GIoU subtracts a penalty based on the smallest box enclosing both boxes, so disjoint boxes still get a useful gradient. DETR uses an L1 term plus a GIoU term for this reason.
The classification loss and the imbalance problem
Binary cross-entropy for one anchor with predicted probability p and label y is -log(p_t), where p_t = p if y = 1 and p_t = 1 - p otherwise.
The trouble is the ratio of anchors. A dense detector evaluates tens of thousands of anchors per image, and only a handful are positive. Most negatives are easy: plain background, classified correctly with high confidence. Each contributes a small loss, but there are so many that their sum can dominate the gradient. The model is trained mostly on what it already knows.
Fixes before focal loss
- Sampling. Faster R-CNN's region proposal network (RPN) samples 256 anchors per image, with at most half positive.
- Hard negative mining. SSD keeps only the negatives with the highest loss, at a ratio of about 3 negatives per positive.
- Two stages. The proposal stage discards most of the easy background, so the second stage sees a more balanced set.
All of these throw information away or add a stage. Focal loss keeps every anchor and changes the loss itself.
Focal loss
Focal loss, introduced with RetinaNet, multiplies cross-entropy by a modulating factor:
FL(p_t) = -alpha_t * (1 - p_t)^gamma * log(p_t)
When an example is easy, p_t is near 1, so (1 - p_t)^gamma is near 0 and the loss is suppressed. When an example is hard, p_t is small and the factor is near 1. With gamma = 0 and alpha = 0.5 you recover cross-entropy up to a constant. RetinaNet uses gamma = 2 and alpha = 0.25.
The alpha_t term is a class weight: alpha for positives, 1 - alpha for negatives. Setting alpha = 0.25 looks backwards, since it down-weights positives. It works because gamma has already suppressed the easy negatives so much that positives no longer need extra weight. The two parameters interact, so tune them together.
import numpy as np
def bce(p, y):
p = np.clip(p, 1e-7, 1 - 1e-7)
return -(y * np.log(p) + (1 - y) * np.log(1 - p))
def focal(p, y, alpha=0.25, gamma=2.0):
p = np.clip(p, 1e-7, 1 - 1e-7)
p_t = np.where(y == 1, p, 1 - p)
alpha_t = np.where(y == 1, alpha, 1 - alpha)
return -alpha_t * (1 - p_t) ** gamma * np.log(p_t)
p = np.array([0.01, 0.1]) # predicted foreground probability
y = np.array([0, 1]) # easy negative, hard positive
print(f"{bce(p, y)[0]:.3e} {focal(p, y)[0]:.3e}") # 1.005e-02 7.538e-07
print(f"{bce(p, y)[1]:.3e} {focal(p, y)[1]:.3e}") # 2.303e+00 4.663e-01The easy negative's loss falls by a factor of about 13,000, while the hard positive's falls by about 5. The hard example now dominates the gradient, which is the intended effect.
Initialization matters
At the start of training, a randomly initialized classifier outputs roughly 0.5 for every anchor. With a huge number of negatives, the loss is large and training can diverge. RetinaNet sets the final classification bias so the initial foreground probability is a small prior pi = 0.01: b = -log((1 - pi) / pi), about -4.6. This lowers the initial loss from the negatives without changing the focal formula.
Common errors
| Symptom | Likely cause |
|---|---|
| Loss is NaN early in training | No prior bias initialization, or `log(0)` from unclipped probabilities |
| High precision, very low recall | Class weight `alpha` too low, or `gamma` too high for the data |
| Boxes drift or jitter despite low loss | Regression loss applied to negatives, or offsets not normalized |
| Loss scales with image size | Normalizing by total anchors instead of `N_pos` |
| Images with no objects cause errors | Division by zero when `N_pos = 0`; use `max(N_pos, 1)` |
Limits of the approach
Focal loss addresses imbalance between easy and hard examples. It does not fix noisy labels: a mislabeled anchor looks like a hard example and receives a large gradient. It also does not remove the need for NMS, because several anchors can still fire on the same object. The next chapters cover NMS and the detectors that rely on this loss.
Exercise
A negative anchor has predicted foreground probability 0.1, so pt = 0.9. Using gamma = 2, by what factor does the focal modulating term (1 - pt)^gamma reduce the cross-entropy loss, ignoring alpha? Then explain why a hard positive with p_t = 0.1 is reduced much less.
Show answer
The modulating term is (1 - 0.9)^2 = 0.01, so the loss is reduced by a factor of 100. For the hard positive with pt = 0.1, the term is (1 - 0.1)^2 = 0.81, so the loss shrinks by only about 19 percent. The factor goes to zero as pt approaches 1, so well-classified examples are suppressed while misclassified ones keep nearly their full loss.