BLOGLLM Logo
Go Pro
Guest
Not signed in
所有博客课程练习面试准备系列标签书签价格
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboard游戏
Articles
练习 / Losses5 of 12 in topic

232. 计算正样本 anchor 的 smooth L1 box regression loss

EasyLosses

重要性 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)
Play with it

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.

0123-3-2-10123residual r
residual r
0.00
smooth L1
0
squared
0
absolute
0
slope of smooth L1
0
smooth L1squaredabsolute

示例 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 在零点附近是平方形式,在远离零点时是线性形式,就像一个从弹簧变成绳子的装置:靠近时很柔和,远离时则是稳定的拉力。

Worked example

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。

主题
Losses
相似题目
  • 直接从 logits 计算二元交叉熵Easy
  • 基于原始 logits 的 label smoothing 交叉熵Easy
  • 计算 multiclass hinge lossEasy
  • 计算 soft Dice lossEasy
所有 Losses 道题目
反馈
232 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def smooth_l1_box_loss(pred, target, labels, beta=1.0):
# your code here
pass
​

Run 会在浏览器中检查这些用例,无需登录。 Submit 会检查所有 3 个测试。

Ctrl/按 + 回车 运行
© BlogLLM, Bengaluru, India关于条款隐私退款DMCA联系我们RSS