AI from scratch · Inside a detector · Stage 5: seeing and reading

Inside a detector

Chapter 9 used a detector as a black box: photo in, boxes with labels and confidences out. This lesson opens it. A detector is a CNN like chapter 6's whose last layer doesn't output 10 class scores but a small grid of predictions, each one saying "is there an object centered here, how far off-center, how big, and what is it". The tricks are in how a box becomes numbers a network can learn, which prediction is responsible for which object, and how you score the result. Then the same machinery, pushed to every pixel, gives segmentation.

1. The grid: one cell is responsible

YOLO ("you only look once") cuts the image into an \(S \times S\) grid. The cell that contains an object's center is responsible for it, and predicts its box. The network's output is a tensor of shape \(S \times S \times (\text{numbers per cell})\): one prediction per cell, all computed in one pass, which is why it's fast. Tap an object below.

The original YOLO used a 7 × 7 grid and predicted 30 numbers per cell. How many numbers does its last layer output?

\(7 \times 7 \times 30 = 1{,}470\): for each cell, two boxes of 5 numbers (center x, y, width, height, objectness) and 20 class scores. One forward pass, every prediction at once.

A detector's output is a grid of predictions, and the cell holding an object's center is the one responsible for finding it.

2. Anchors, and a box as four learnable numbers

Predicting a box's width from scratch is hard: a pedestrian is tall and thin, a bus long and low. So each cell gets a few anchor boxes, typical shapes taken from the training data (clustered with k-means, in fact). An object is assigned to the anchor whose shape fits it best (highest IoU when both are centered together), and the network predicts only a correction to that anchor:

\[ c_x = (g_x + \sigma(t_x)) \cdot \text{cell}, \quad c_y = (g_y + \sigma(t_y)) \cdot \text{cell}, \quad w = a_w\, e^{t_w}, \quad h = a_h\, e^{t_h} \]

Here \((g_x, g_y)\) is the cell, \(\sigma\) keeps the center inside it (chapter 3's sigmoid), and the size is the anchor's \(a_w, a_h\) stretched by \(e^{t}\). The widget's readout shows the four target numbers \(t_x, t_y, t_w, t_h\) for the object you tapped. Each cell also predicts an objectness score (is there an object centered here?) and class scores (a softmax, chapter 5).

Why predict the logarithm of the size ratio?
  1. A 10-pixel error in width is a disaster for a 20-pixel bicycle and nothing for a 400-pixel bus. Errors should be relative, not absolute.
  2. With \(w = a_w e^{t_w}\), the target is \(t_w = \ln(w / a_w)\). A box twice the anchor's width has \(t_w = \ln 2 \approx 0.69\) whatever the sizes involved; half has \(-0.69\).
  3. So "twice too big" and "half too small" cost the same in a squared-error loss, at every scale: the loss is about ratios, which is what IoU cares about.
  4. And \(e^{t}\) is always positive, so the network can never predict a negative width, whatever number it outputs.
  5. The center uses a sigmoid for a similar reason: \(\sigma(t_x)\) is always between 0 and 1, so the predicted center can't wander out of the responsible cell, which keeps early training stable.

Each cell refines a few typical anchor shapes: a sigmoid offset for the center and a log size ratio, so errors are relative and widths stay positive.

3. The loss: several jobs in one number

Training adds up a term per job, each computed only where it applies:

TermWhereLoss
Box position and sizeonly the responsible cell and anchorSquared error on \(t_x, t_y, t_w, t_h\), or a loss built from IoU directly
Objectnessevery cell: 1 where an object is centered, 0 elsewhereLog loss (chapter 3)
Classonly cells with an objectCross-entropy (chapter 5)

Most cells are empty, so the objectness term is dominated by "nothing here" examples (chapter 12's imbalance); detectors weight the terms (YOLO multiplies the box term by 5 and the empty cells' objectness by 0.5) or use a focal loss that turns down easy, confident examples. At test time: keep cells whose objectness × class probability passes a threshold, decode their boxes, and run non-maximum suppression (chapter 9).

Why is the box loss computed only at the responsible cell?

Every cell outputs box numbers, but only the responsible one has a target. Empty cells are trained only to say "no object" through objectness; their boxes are ignored, and at test time low objectness filters them out.

A detector's loss is a sum of jobs: where the box is (only where an object is), whether there is an object (everywhere), and what it is.

4. Scoring a detector: mean average precision

Chapter 9 scored detections with precision and recall at one confidence threshold. A detector's standard score, mAP, sweeps the threshold, like chapter 12's precision-recall curve:

  1. For one class, sort all detections over the whole test set by confidence.
  2. Go down the list: each detection that overlaps an unclaimed real object with IoU ≥ 0.5 is a true positive, anything else (including a second box on an already-found object) a false positive.
  3. After each detection, compute precision and recall so far; the area under that curve is the class's average precision (AP).
  4. Average over classes: mAP. COCO's version also averages over IoU thresholds from 0.5 to 0.95, which rewards tight boxes.

mAP sweeps the confidence threshold: the area under each class's precision-recall curve, averaged over classes (and on COCO over IoU thresholds too).

5. Segmentation: a label for every pixel

Semantic segmentation labels every pixel (road, car, person, sky); instance segmentation also separates the individual cars. The classic architecture is U-Net: an encoder that shrinks the image like any CNN (more channels, less resolution: what is there), a decoder that grows it back to full size (where exactly), and skip connections that hand each decoder level the encoder's sharp, high-resolution maps from the same level, so boundaries come out crisp.

64 × 64
16 ch
— skip →
— skip →
64 × 64
16 ch → mask
32 × 32
32 ch
— skip →
32 × 32
32 ch
16 × 16
64 ch

The loss is per-pixel cross-entropy (or log loss for one class). The scores compare the predicted mask \(P\) with the true mask \(M\):

\[ \text{IoU} = \frac{|P \cap M|}{|P \cup M|}, \qquad \text{Dice} = \frac{2\,|P \cap M|}{|P| + |M|} \]

A segmentation model marks every pixel of a scan as "healthy", and tumors cover 1% of the pixels. Its pixel accuracy is 99%. What's its Dice score for the tumor class?

Chapter 12's base-rate trap, per pixel. Dice and IoU look only at the class you care about, which is why segmentation reports them instead of pixel accuracy.

Segmentation labels every pixel: U-Net shrinks to understand and grows back to place, with skips carrying sharp detail across, and Dice or IoU score the class that matters.

Where it breaks: small, crowded, and shapes no anchor fits

6. What to carry forward

All lessons: AI from scratch. Papers: Redmon et al., "You Only Look Once" (2016) and YOLO9000 (2017) for anchors; Ronneberger et al., "U-Net" (2015).

Last updated