Sub topic 9
Removing duplicates with non-maximum suppression
This chapter assumes you can read basic Python, and that you know what IoU is and how anchors produce many candidate boxes per object. The previous chapters covered both. Here you will see why detectors emit duplicates, how non-maximum suppression (NMS) removes them, and where the procedure fails.
Why duplicates appear
An anchor-based detector scores thousands of anchors per image. During training, every anchor with high enough IoU against a ground-truth box counts as a positive (see the earlier chapter on label assignment). The network is therefore trained to fire on many neighboring anchors for the same object.
At inference time this produces a cluster of boxes around each object. Each box has a similar position and a similar class score. If you returned all of them, one dog would appear as ten dogs, and your precision would collapse.
NMS is a post-processing step that keeps the best box in each cluster and drops the rest. It is not learned. It runs after the network and takes no gradients.
The greedy algorithm
Greedy NMS works on one class at a time:
- Sort boxes by score, highest first.
- Take the top box and add it to the keep list.
- Remove every remaining box whose IoU with that box is above a threshold.
- Repeat from step 2 until no boxes remain.
Here is a complete implementation. It includes iou() so you can run it as shown.
def iou(a, b):
"""IoU of two boxes given as (x1, y1, x2, y2)."""
ix1, iy1 = max(a[0], b[0]), max(a[1], b[1])
ix2, iy2 = min(a[2], b[2]), min(a[3], b[3])
inter = max(0.0, ix2 - ix1) * max(0.0, iy2 - iy1)
area_a = (a[2] - a[0]) * (a[3] - a[1])
area_b = (b[2] - b[0]) * (b[3] - b[1])
union = area_a + area_b - inter
return inter / union if union > 0 else 0.0
def nms(boxes, scores, iou_threshold=0.5):
"""Greedy NMS. Returns indices of kept boxes."""
order = sorted(range(len(boxes)), key=lambda i: scores[i], reverse=True)
keep = []
while order:
best = order.pop(0)
keep.append(best)
order = [j for j in order if iou(boxes[best], boxes[j]) <= iou_threshold]
return keep
boxes = [(0, 0, 10, 10), (1, 1, 11, 11), (50, 50, 60, 60)]
scores = [0.9, 0.8, 0.7]
print(nms(boxes, scores)) # [0, 2]Box 1 overlaps box 0 with IoU 81 / 119, about 0.68. That is above 0.5, so it is suppressed. Box 2 is far away and survives.
Choosing the IoU threshold
The threshold controls a trade-off between two failure modes.
| Threshold | Effect | Typical failure |
|---|---|---|
| Low (about 0.3) | Aggressive suppression | Two real, nearby objects merge into one detection |
| Medium (about 0.5) | Common default | Balanced for most datasets |
| High (about 0.7) | Lenient suppression | Duplicates survive and count as false positives |
Crowded scenes, such as pedestrians or stacked boxes, push you toward a higher threshold. Sparse scenes with large objects tolerate a lower one. The right value depends on the dataset, so tune it on validation data rather than copying a default.
Per-class NMS
A box labeled "person" and a box labeled "backpack" can legitimately overlap. Suppressing across classes would delete real objects. Standard practice is to run NMS separately for each class.
Looping over classes works but is slow on a GPU. A common trick shifts each class's boxes by a class-dependent offset so that boxes of different classes can never overlap. Then one NMS call handles everything.
def batched_nms(boxes, scores, labels, iou_threshold=0.5):
"""Class-aware NMS using a per-class coordinate offset."""
offset = max(max(b) for b in boxes) + 1
shifted = [
(b[0] + l * offset, b[1] + l * offset, b[2] + l * offset, b[3] + l * offset)
for b, l in zip(boxes, labels)
]
return nms(shifted, scores, iou_threshold)
boxes = [(0, 0, 10, 10), (1, 1, 11, 11), (0, 0, 10, 10)]
scores = [0.9, 0.8, 0.7]
labels = [0, 0, 1]
print(batched_nms(boxes, scores, labels)) # [0, 2]Boxes 0 and 1 share class 0, so box 1 is suppressed. Box 2 has the same coordinates as box 0 but class 1, so it is moved away and kept. Libraries such as torchvision provide this as torchvision.ops.batched_nms.
Where NMS sits in a real pipeline
Running the quadratic loop over every anchor would be wasteful. A typical inference pipeline does the following:
- Decode the regression outputs into boxes (see the box encoding chapter).
- Discard boxes with a class score below a small cutoff, such as 0.05.
- Keep only the top-k boxes per class or per image, for example 1000.
- Run per-class NMS.
- Keep at most N final detections, for example 100.
Steps 2 and 3 matter for speed. Greedy NMS compares boxes pairwise, so its cost grows roughly with the square of the number of boxes in the worst case.
Known weaknesses
Greedy NMS has several well-documented problems.
- Occlusion and crowds. Two people standing close together have heavily overlapping boxes. The lower-scoring true detection gets suppressed because the algorithm only sees overlap, not whether the boxes cover different objects.
- Score and localization mismatch. The classification score picks the winner, but a higher score does not guarantee a better-fitting box. NMS can keep a confident but sloppy box and discard a tighter one.
- Hard threshold. A box with IoU 0.51 is deleted and one with 0.49 is untouched. The result is sensitive to small shifts.
- Extra hyperparameters. The threshold, score cutoff, and top-k all affect accuracy, and they are chosen by hand.
- Not differentiable. The network is never trained with NMS in the loop. It is trained to produce duplicates, and NMS cleans up afterward.
Variants
Soft-NMS replaces deletion with score decay. Instead of removing an overlapping box, it multiplies its score by a factor that shrinks as IoU grows. A Gaussian version uses exp(-iou**2 / sigma). Overlapping boxes in crowds then survive with lower scores instead of vanishing.
import math
def soft_nms(boxes, scores, sigma=0.5, score_threshold=0.001):
"""Gaussian Soft-NMS. Returns (index, decayed score) pairs in pick order."""
scores = list(scores)
remaining = list(range(len(boxes)))
kept = []
while remaining:
best = max(remaining, key=lambda i: scores[i])
remaining.remove(best)
kept.append((best, scores[best]))
for j in remaining:
scores[j] *= math.exp(-(iou(boxes[best], boxes[j]) ** 2) / sigma)
remaining = [j for j in remaining if scores[j] >= score_threshold]
return kept
boxes = [(0, 0, 10, 10), (1, 1, 11, 11), (50, 50, 60, 60)]
scores = [0.9, 0.8, 0.7]
print([(i, round(s, 2)) for i, s in soft_nms(boxes, scores)])
# [(0, 0.9), (2, 0.7), (1, 0.32)]The second box is not deleted. Its score drops from 0.8 to about 0.32, and you filter by score afterward.
Other variants include weighted box fusion, which averages overlapping boxes instead of picking one, and learned NMS, which trains a small network to decide which boxes to keep.
Why DETR removes the need for NMS
All of these fixes address a problem the training scheme created: many positives per object. DETR, covered in later chapters, trains with one-to-one Hungarian matching. Each ground-truth object is assigned exactly one prediction, and every other prediction is trained toward "no object". The model learns to suppress its own duplicates, so no NMS is needed at inference.
Exercise
Box A is (0, 0, 10, 10) with score 0.9. Box B is (2, 0, 12, 10) with score 0.8. Both have the same class. Does greedy NMS keep B at an IoU threshold of 0.5? What about 0.7?
Show answer
The intersection is 8 x 10 = 80. The union is 100 + 100 - 80 = 120. IoU = 80 / 120, about 0.667. At threshold 0.5, 0.667 is above the threshold, so B is suppressed and only A is kept. At threshold 0.7, 0.667 is not above the threshold, so B is kept and both boxes are returned.
Exercise
Why does per-class NMS help in a street scene, and what failure would you expect if you ran class-agnostic NMS with a low threshold?
Show answer
Objects of different classes, such as a person carrying a backpack or a rider on a bicycle, often overlap heavily. Per-class NMS only compares boxes of the same class, so those legitimate overlaps survive. Class-agnostic NMS with a low threshold would suppress the lower-scoring box of an overlapping pair even though it is a different object, which lowers recall.