A dense detector should not regress arbitrary boxes from scratch at every location. Anchor boxes turn the problem into residual regression around structured candidate boxes.
Attach anchors to spatial locations, usually feature-map cells mapped back to image coordinates.
For each anchor, predict class and box offset.
After the forward pass, non-maximum suppression prunes overlapping high-confidence predictions.
Core of SSD, RetinaNet, and the region proposal network in Faster R-CNN. Some modern detectors are anchor-free, but the same ideas — dense classification, localization, and NMS — remain central.
Coordinates and feature maps
Keep three coordinate systems separate:
image coordinates: box corners or centers measured in pixels;
feature-map cells: locations after CNN downsampling, each with a receptive field in the image;
normalized anchors: candidate boxes parameterized relative to image width/height or to a feature-map stride.
In toy code we generate anchors at image pixels for clarity. In production detectors, anchors are usually tied to feature-map locations so each prediction uses the local receptive field.
Generating anchors
At each pixel center, generate boxes for n scales and m aspect ratios — but only those involving the smallest scale or smallest ratio, giving n + m - 1 boxes per pixel (not nm):
\text{anchor width} = w s\sqrt{r}, \quad \text{anchor height} = h s / \sqrt{r}.
def multibox_prior(data, sizes, ratios):"""Generate anchor boxes with different shapes centered on each pixel.""" in_height, in_width = data.shape[-2:] device, num_sizes, num_ratios = data.device, len(sizes), len(ratios) boxes_per_pixel = (num_sizes + num_ratios -1) size_tensor = d2l.tensor(sizes, device=device) ratio_tensor = d2l.tensor(ratios, device=device)# Offsets are required to move the anchor to the center of a pixel. Since# a pixel has height=1 and width=1, we choose to offset our centers by 0.5 offset_h, offset_w =0.5, 0.5 steps_h =1.0/ in_height # Scaled steps in y axis steps_w =1.0/ in_width # Scaled steps in x axis
Generating anchors: centers and sizes
Anchor centers sit at pixel centers in normalized coordinates; widths and heights follow the formula above:
# Generate all center points for the anchor boxes center_h = (torch.arange(in_height, device=device) + offset_h) * steps_h center_w = (torch.arange(in_width, device=device) + offset_w) * steps_w shift_y, shift_x = torch.meshgrid(center_h, center_w, indexing='ij') shift_y, shift_x = shift_y.reshape(-1), shift_x.reshape(-1)# Generate `boxes_per_pixel` number of heights and widths that are later# used to create anchor box corner coordinates (xmin, xmax, ymin, ymax) w = torch.cat((size_tensor * torch.sqrt(ratio_tensor[0]), sizes[0] * torch.sqrt(ratio_tensor[1:])))\* in_height / in_width # Handle rectangular inputs h = torch.cat((size_tensor / torch.sqrt(ratio_tensor[0]), sizes[0] / torch.sqrt(ratio_tensor[1:])))
Generating anchors: corners
Pair every center with each of its n + m - 1 half-widths and half-heights; the sums are the corners (x_1, y_1, x_2, y_2):
# Divide by 2 to get half height and half width anchor_manipulations = torch.stack((-w, -h, w, h)).T.repeat( in_height * in_width, 1) /2# Each center point will have `boxes_per_pixel` number of anchor boxes, so# generate a grid of all anchor box centers with `boxes_per_pixel` repeats out_grid = torch.stack([shift_x, shift_y, shift_x, shift_y], dim=1).repeat_interleave(boxes_per_pixel, dim=0) output = out_grid + anchor_manipulationsreturn output.unsqueeze(0)
Anchor tensor shape
For a h \times w feature map, total anchors = hw(n+m-1). Stored as a tensor of shape (1, num_anchors, 4):
We need a similarity measure between two boxes to know which anchor matches which ground truth.
\text{IoU}(A, B) = \frac{|A \cap B|}{|A \cup B|}.
IoU = intersection area / union area.
Intersection over Union (cont.)
box_iou computes all pairwise IoUs between two lists of boxes at once, as an (n_1, n_2) matrix:
def box_iou(boxes1, boxes2):"""Compute pairwise IoU across two lists of anchor or bounding boxes.""" box_area =lambda boxes: ((boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1]))# Shape of `boxes1`, `boxes2`, `areas1`, `areas2`: (no. of boxes1, 4),# (no. of boxes2, 4), (no. of boxes1,), (no. of boxes2,) areas1 = box_area(boxes1) areas2 = box_area(boxes2)# Shape of `inter_upperlefts`, `inter_lowerrights`, `inters`: (no. of# boxes1, no. of boxes2, 2) inter_upperlefts = torch.max(boxes1[:, None, :2], boxes2[:, :2]) inter_lowerrights = torch.min(boxes1[:, None, 2:], boxes2[:, 2:]) inters = (inter_lowerrights - inter_upperlefts).clamp(min=0)# Shape of `inter_areas` and `union_areas`: (no. of boxes1, no. of boxes2) inter_areas = inters[:, :, 0] * inters[:, :, 1] union_areas = areas1[:, None] + areas2 - inter_areasreturn inter_areas / union_areas
Matching anchors to ground truth
For each anchor box, decide which ground-truth box (if any) it should learn to predict. Common rule: greedy assignment by highest IoU, with a threshold (e.g. 0.5) for “positive” matches:
Anchor → GT assignment by IoU.
Matching anchors to ground truth (cont.)
def assign_anchor_to_bbox(ground_truth, anchors, device, iou_threshold=0.5):"""Assign closest ground-truth bounding boxes to anchor boxes.""" num_anchors, num_gt_boxes = anchors.shape[0], ground_truth.shape[0]# Element x_ij in the i-th row and j-th column is the IoU of the anchor# box i and the ground-truth bounding box j jaccard = box_iou(anchors, ground_truth)# Initialize the tensor to hold the assigned ground-truth bounding box for# each anchor anchors_bbox_map = torch.full((num_anchors,), -1, dtype=torch.long, device=device)# Assign ground-truth bounding boxes according to the threshold max_ious, indices = torch.max(jaccard, dim=1) anc_i = torch.nonzero(max_ious >= iou_threshold).reshape(-1) box_j = indices[max_ious >= iou_threshold] anchors_bbox_map[anc_i] = box_j col_discard = torch.full((num_anchors,), -1) row_discard = torch.full((num_gt_boxes,), -1)for _ inrange(num_gt_boxes): max_idx = torch.argmax(jaccard) # Find the largest IoU box_idx = (max_idx % num_gt_boxes).long() anc_idx = torch.div(max_idx, num_gt_boxes, rounding_mode='floor') anchors_bbox_map[anc_idx] = box_idx jaccard[:, box_idx] = col_discard jaccard[anc_idx, :] = row_discardreturn anchors_bbox_map
Labels and offsets
A matched anchor learns:
Class = the ground-truth class.
Offset = the parameterized residual between anchor and ground truth, normalized by per-component mean/std:
Each output row is (class_id, confidence, x1, y1, x2, y2). Rows with class -1 have been suppressed or filtered out; the remaining rows are the detector’s final boxes.