Build YOLO-style training targets on a grid with anchors

Why it matters YOLOv2 and v3 style training, and many anchor-based single-stage detectors, build targets like this.

A YOLO-style detector makes the grid cell containing an object's center, with the best-shaped anchor, responsible for predicting it.

Write yolo_targets(boxes, labels, S, img_size, anchors). boxes is (n, 4) as (cx, cy, w, h) in pixels; labels is (n,); the image is img_size x img_size split into an S x S grid with cell size c = img_size / S; anchors is a list of A (aw, ah) sizes in pixels. Return a float array T of shape (S, S, A, 6), zeros by default. For each box in order: pick the anchor with the highest shape IoU, inter = min(w, aw) * min(h, ah), iou = inter / (w * h + aw * ah - inter) (first anchor wins ties). The row is i = min(int(cy // c), S - 1) and the column is j = min(int(cx // c), S - 1). Set T[i, j, a] = [1, cx / c - j, cy / c - i, log(w / aw), log(h / ah), label]. Later boxes overwrite earlier ones in the same slot.

Signaturedef yolo_targets(boxes, labels, S, img_size, anchors)

Example

one box (cx 50, cy 10, w 20, h 40), label 3, S = 2, img_size = 64, anchors [(20, 20), (20, 40)] sets T[0, 1, 1] = [1, 0.5625, 0.3125, 0, 0, 3] and leaves the rest 0.

Understand the idea

YOLO splits the image into an S x S grid. Each object is handed to the one cell that contains its center, and within that cell to the anchor whose shape is most like the object, tall or wide. That slot must learn to say there is an object here, where exactly in the cell its center is, how much to stretch the anchor, and which class it is. Like assigning each guest to the table nearest where they stand and the chair that fits them best.

Tiny example: a 64 pixel image, 2 x 2 grid, cell 32. Center (50, 10) is in row 10 // 32 = 0, column 50 // 32 = 1. A 20 x 40 box matches the (20, 40) anchor exactly. Offsets: 50 / 32 - 1 = 0.5625 and 10 / 32 = 0.3125; log size ratios 0.

Rule: T[i, j, a] = [1, cx/c - j, cy/c - i, log(w/aw), log(h/ah), cls] with i from cy and j from cx.

The loss is then computed slot by slot against these targets.

Shapes and data flow

boxes (n,4) -> T (S, S, A, 6) with [obj, tx, ty, tw, th, cls]
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: exampleyolo_targets([[50.0, 10.0, 20.0, 40.0]], [3], 2, 64, [(20.0, 20.0), (20.0, 40.0)])[0, 1, 1]
  • Sample 2: all zero elsewherefloat(yolo_targets([[50.0, 10.0, 20.0, 40.0]], [3], 2, 64, [(20.0, 20.0), (20.0, 40.0)]).sum())