Sub topic 7
Deciding which anchors are positives
This chapter assumes you know IoU, how anchors tile a feature map, and how box offsets are encoded and decoded. It also assumes you are comfortable with NumPy and with classification and regression losses.
Why detectors need an assignment step
A detector with anchors predicts a class score and four box offsets for every anchor. A typical image has a handful of ground-truth boxes and tens of thousands of anchors. The loss needs a training target for each anchor, and the dataset only provides the boxes.
Label assignment (also called target assignment or matching) turns the ground-truth boxes into a target for every anchor. Each anchor gets one of three outcomes:
- Positive: the anchor is responsible for one specific ground-truth box. Its class target is that box's class, and its regression target is the offsets that turn the anchor into that box.
- Negative: the anchor is background. Its class target is "no object" and it has no regression loss.
- Ignored: the anchor is ambiguous and contributes nothing to the loss.
The assignment rule decides which anchors learn to fire on an object and which learn to stay quiet. A poor rule hurts accuracy even when the network and loss are good.
The standard IoU rule
The classic rule compares each anchor with each ground-truth box using IoU. It uses two thresholds, a positive threshold and a negative threshold.
- Compute the IoU between every anchor and every ground-truth box. The result is a matrix with one row per anchor and one column per box.
- For each anchor, take the ground-truth box with the highest IoU. Call that value the anchor's best IoU.
- If the best IoU is at least the positive threshold, the anchor is positive and is matched to that box.
- If the best IoU is below the negative threshold, the anchor is negative.
- If it falls between the two thresholds, the anchor is ignored.
The thresholds differ between detectors:
| Detector | Positive if | Negative if | Notes |
|---|---|---|---|
| Faster R-CNN (RPN) | IoU ≥ 0.7, or highest IoU for a box | IoU < 0.3 | Anchors crossing the image border are dropped in training. Each minibatch samples 256 anchors, at most half positive. |
| SSD | IoU ≥ 0.5 | Everything else, but only the hardest are used | Hard negative mining keeps about 3 negatives per positive. |
| RetinaNet | IoU ≥ 0.5 | IoU < 0.4 | Anchors with IoU in [0.4, 0.5) are ignored. Focal loss handles the imbalance, so no sampling is used. |
The gap between the thresholds exists because an anchor with IoU 0.45 is a bad training example either way. Labeling it positive teaches the network to fire on a poor box. Labeling it negative teaches it to suppress an anchor that overlaps the object quite well. Ignoring it avoids both problems.
The forced match for every ground-truth box
The threshold rule alone has a flaw. A small or oddly shaped object may not reach the positive threshold with any anchor. Then the object gets no positive anchors, and the network never learns to detect it.
The fix is a second step. For each ground-truth box, find the anchor with the highest IoU and mark it positive, even if its IoU is below the threshold. This guarantees every object has at least one positive anchor. Most implementations run this step after the threshold step, so it overrides a negative or ignored label.
A worked implementation
The code below implements both steps with NumPy. It uses the RetinaNet thresholds, 0.5 and 0.4, and it labels positives 1, negatives 0, and ignored anchors -1. The anchors are chosen so that each outcome appears once.
import numpy as np
def iou_matrix(anchors, gts):
"""Pairwise IoU. anchors: (A, 4), gts: (G, 4), boxes as x1, y1, x2, y2."""
ix1 = np.maximum(anchors[:, None, 0], gts[None, :, 0])
iy1 = np.maximum(anchors[:, None, 1], gts[None, :, 1])
ix2 = np.minimum(anchors[:, None, 2], gts[None, :, 2])
iy2 = np.minimum(anchors[:, None, 3], gts[None, :, 3])
inter = np.clip(ix2 - ix1, 0, None) * np.clip(iy2 - iy1, 0, None)
area_a = (anchors[:, 2] - anchors[:, 0]) * (anchors[:, 3] - anchors[:, 1])
area_g = (gts[:, 2] - gts[:, 0]) * (gts[:, 3] - gts[:, 1])
union = area_a[:, None] + area_g[None, :] - inter
return inter / np.maximum(union, 1e-9)
def assign(anchors, gts, pos_thr=0.5, neg_thr=0.4):
"""Return (labels, matched_gt) where labels are 1, 0 or -1 (ignore)."""
ious = iou_matrix(anchors, gts)
matched_gt = ious.argmax(axis=1)
best_iou = ious.max(axis=1)
labels = np.full(len(anchors), -1)
labels[best_iou < neg_thr] = iou >= pos_thr] = 1
# Forced match: the best anchor for each ground-truth box is positive.
for g, a in enumerate(=0)):
labels[a] = 1
matched_gt[a] = g
return labels, matched_gt
anchors = np.array([
[ 10], # IoU 1.00 with box 0
[2, 0, 12, 10], # IoU 0.67 with box 0
[410], # IoU 0.43 with box 0 -> ignored
[5, 0, 15, 10], # IoU 0.33 ative
[50, 50, 60, 60], # no overlap -> negative
[28, 28, 38, 38], # IoU 0.16 with box 1 -> forced match
], dtype=float)
gts = np.array([[0, 0, 10, 10], [30, 30, 34, 34]],els, matched = assign(anchors, gts)
print(labels.tolist()) # [1, 1, -1, 0, 0, 1]
print(matched.tolist()) # [0, 0, 0, 0, 0, 1]The small box (30, 30, 34, 34) has area 16, and the best anchor covers it with IoU 0.16. The threshold step would label that anchor negative. The forced match turns it positive. The matched array tells the loss which box supplies the regression target for each positive anchor.
Edge cases to watch
- One anchor, two overlapping boxes. Each anchor is matched to the single box with the highest IoU. In crowded scenes this means a box can lose anchors to a neighbor. The
argmaxrule is deterministic, but ties go to the first box, so ordering can matter. - One anchor chosen by two boxes in the forced step. If two boxes have the same best anchor, the later box overwrites the earlier one in the code above. That leaves the earlier box with fewer positives. Some implementations resolve this with a global greedy match instead.
- Crowd and ignore regions. Datasets such as COCO mark "crowd" regions. Anchors that overlap them strongly should be ignored, not labeled negative. Otherwise the network is punished for detecting real people in a dense group.
- Imbalance. Even with thresholds, negatives vastly outnumber positives, often by more than 1000 to 1. Faster R-CNN samples a balanced minibatch, SSD mines hard negatives, and RetinaNet uses focal loss. The assignment step does not fix imbalance by itself.
- Threshold sensitivity. Raising the positive threshold gives fewer, better-localized positives. Lowering it gives more positives with noisier regression targets. Cascade R-CNN uses this effect by training successive stages with increasing thresholds.
Beyond fixed IoU thresholds
Fixed thresholds treat every object the same, but objects differ in size and shape. A tiny object has few anchors with IoU above 0.5, while a large one may have hundreds. Later methods make the rule adaptive:
- ATSS sets a threshold per ground-truth box from the statistics (mean plus standard deviation) of IoUs among the nearest candidate anchors. This removes most of the hand-tuned threshold dependence.
- Center sampling (FCOS). Anchor-free detectors treat feature-map locations as positives when they fall inside a ground-truth box, usually near its center. Chapter content on FCOS covers this in detail.
- Dynamic assignment (OTA, SimOTA). The assignment depends on the current network predictions through a cost that combines classification and localization, so it changes during training.
- One-to-one matching. DETR assigns exactly one prediction per object with the Hungarian algorithm. This removes the need for NMS and is the subject of a later chapter.
The IoU rule is the baseline that these methods modify. Each one changes which candidates count as positives and how many each object gets.
Compute assignment on anchors in image coordinates, with the same coordinate convention as the ground truth. A common bug is mixing normalized (0 to 1) boxes with pixel boxes, which produces IoU of zero everywhere. No anchor then passes the threshold, and the forced match quietly makes one meaningless anchor positive per box.Exercise
Using the thresholds 0.5 (positive) and 0.4 (negative), an anchor has a best IoU of 0.45 with a ground-truth box. A second anchor is the highest-IoU anchor for a small box, with IoU 0.30. How is each anchor labeled, and why?
Show answer
The first anchor is ignored, because 0.45 lies between the negative threshold (0.4) and the positive threshold (0.5), so it contributes no loss. The second anchor is positive, because the forced-match step marks the best anchor of every ground-truth box as positive even when its IoU is below the positive threshold. This guarantees the small box has at least one positive anchor.
Exercise
Why does Faster R-CNN's RPN sample a minibatch of 256 anchors instead of using all anchors in the loss, and what does RetinaNet use instead?
Show answer
Almost all anchors are negative, so a loss over all anchors would be dominated by easy background examples. The RPN samples up to 128 positives and fills the rest with negatives to keep the batch balanced. RetinaNet uses every anchor and applies focal loss, which down-weights easy negatives so they stop dominating the gradient.