Compute smooth L1 box regression loss over positive anchors
Why it matters Faster R-CNN, RetinaNet and SSD all train their box heads with this loss.
Object detectors regress box offsets with smooth L1: squared for small errors, linear for big ones, and only on anchors that matched an object.
Write smooth_l1_box_loss(pred, target, labels, beta=1.0). pred and target are (A, 4) box offsets and labels is (A,) with 1 for foreground, 0 for background and -1 for ignored. For each element d = pred - target: loss = 0.5 * d^2 / beta if |d| < beta else |d| - 0.5 * beta. Sum over the 4 coordinates of foreground anchors only, then divide by max(1, number of foreground anchors). Return a float.
def smooth_l1_box_loss(pred, target, labels, beta=1.0)Example
pred = [[0.5, 0, 0, 2], [9, 9, 9, 9]], target = zeros, labels = [1, 0] gives 0.125 + 1.5 = 1.625.
Understand the idea
Box regression errors can be huge for badly matched anchors. Squared error would let those outliers dominate, while plain absolute error has a sharp corner at zero that makes small corrections jumpy. Smooth L1 is squared near zero and linear far away, like a spring that turns into a rope: gentle when close, steady pull when far.
Tiny example: beta = 1. Error 0.5 is small: 0.5 * 0.25 = 0.125. Error 2 is big: 2 - 0.5 = 1.5. One foreground anchor, so the loss is 1.625. The background anchor with errors of 9 is skipped.
Rule: l(d) = 0.5 d^2 / beta if |d| < beta else |d| - 0.5 beta; loss = sum over foreground coords / max(1, num_fg).
Two-stage and one-stage detectors use this for the four box offsets.