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?
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?
- 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.
- 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\).
- 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.
- And \(e^{t}\) is always positive, so the network can never predict a negative width, whatever number it outputs.
- 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:
| Term | Where | Loss |
|---|---|---|
| Box position and size | only the responsible cell and anchor | Squared error on \(t_x, t_y, t_w, t_h\), or a loss built from IoU directly |
| Objectness | every cell: 1 where an object is centered, 0 elsewhere | Log loss (chapter 3) |
| Class | only cells with an object | Cross-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?
- To make training faster
- The other cells have no object to describe: their box numbers mean nothing, and a loss on them would train the network to predict garbage
- Because the other cells don't predict boxes
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:
- For one class, sort all detections over the whole test set by confidence.
- 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.
- After each detection, compute precision and recall so far; the area under that curve is the class's average precision (AP).
- 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.
16 ch
16 ch → mask
32 ch
32 ch
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?
- 0: it found none of the tumor pixels
- 0.99
- 0.5
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
- Small objects. After five halvings, a cell covers 32 × 32 pixels. A 10-pixel pedestrian far away is a fraction of one cell's view, and its features were averaged away by the pooling. Detectors add finer grids from earlier layers (feature pyramids), and still miss more small objects than big ones.
- Crowds. Two people whose centers fall in the same cell compete for one cell's few anchors. Turn the widget's grid down to 3 × 3 and watch objects share cells. Finer grids and more anchors help; so does checking recall on crowded test images specifically.
- Shapes no anchor fits. Anchors are chosen from the training set's boxes. A detector trained on street photos, then asked to find long trains or rotated text, starts from anchors that don't resemble them. Newer "anchor-free" detectors (FCOS, CenterNet) predict distances to the box edges directly, and DETR uses attention (chapter 7) to output a set of boxes with no anchors and no non-maximum suppression at all.
6. What to carry forward
- The output is a grid; the cell holding an object's center is responsible for it.
- Boxes are learned as corrections to anchors: \(\sigma(t)\) for the center, \(e^{t}\) for the size (relative errors, positive widths).
- The loss adds box, objectness and class terms, each where it applies; empty cells dominate, so weight or use focal loss.
- mAP is the area under precision-recall per class, averaged; COCO averages IoU thresholds too.
- Segmentation: U-Net with skip connections; score with Dice or IoU, never pixel accuracy.
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