232. 计算正样本 anchor 的 smooth L1 box regression loss
重要性 Faster R-CNN、RetinaNet 和 SSD 都在使用这种 loss 来训练它们的 box heads。
目标检测器使用 smooth L1 来回归 box offsets:对于小误差使用平方损失,对于大误差使用线性损失,且仅在与物体匹配的 anchors 上计算。
编写 smooth_l1_box_loss(pred, target, labels, beta=1.0)。pred 和 target 是 (A, 4) 的 box offsets,labels 是 (A,),其中 1 表示 foreground,0 表示 background,-1 表示 ignored。对于每个元素 d = pred - target:如果 |d| < beta,则 loss = 0.5 * d^2 / beta;否则 loss = |d| - 0.5 * beta。仅对 foreground anchors 的 4 个坐标进行求和,然后除以 max(1, foreground anchors 的数量)。返回一个 float。
def smooth_l1_box_loss(pred, target, labels, beta=1.0)Smooth L1 between squared and absolute error
Inside |r| < beta the loss is quadratic, outside it is linear, so large box errors do not blow up the gradient.
- residual r
- 0.00
- smooth L1
- 0
- squared
- 0
- absolute
- 0
- slope of smooth L1
- 0
示例 1
输入: pred = [[0.5, 0, 0, 2], [9, 9, 9, 9]], target = zeros, labels = [1, 0]
输出: 0.125 + 1.5 = 1.625
示例 2
输入: pred = [[0.5, 0.0, 0.0, 2.0], [9.0, 9.0, 9.0, 9.0]], target = [[0.0] * 4, [0.0] * 4], labels = [1, 0]
输出: 1.625
示例 3
输入: pred = [[0.1, -0.2, 0.05, 0.3], [1.0, 0.0, -1.0, 0.5], [0.0, 0.0, 0.0, 0.0]], target = [[0.0, 0.0, 0.0, 0.0], [0.5, 0.5, 0.5, 0.5], [3.0, 3.0, 3.0, 3.0]], labels = [1, 1, -1], beta = 1 / 9
输出: 1.389236
约束条件
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 3 tests to be accepted.
提示 1
先通过 labels == 1 掩码(mask)行;background 和 ignored 行不贡献任何 loss。
提示 2
使用 np.where 处理两个分支。
提示 3
labels == 1 用于选取 foreground。
提示 4
max(1, count) 用于避免除以零。
常见错误
- 包含了 ignored anchors。
- 按所有 anchors 进行归一化。
理解思路
对于匹配不佳的 anchors,box regression error 可能会非常大。平方误差会让这些离群值占据主导地位,而普通的绝对误差在零点处过于尖锐,会导致微小的修正产生剧烈跳动。Smooth L1 在零点附近是平方形式,在远离零点时是线性形式,就像一个从弹簧变成绳子的装置:靠近时很柔和,远离时则是稳定的拉力。
beta = 1. Error 0.5 很小: 0.5 * 0.25 = 0.125. Error 2 很大: 2 - 0.5 = 1.5. 只有一个 foreground anchor,所以 loss 是 1.625. Error 为 9 的 background anchor 被跳过。
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)和单阶段(one-stage)检测器都使用这种方式来处理四个 box offsets。