A Tiny Grid Detector Trained from Scratch
The previous lessons took detectors apart: IoU and evaluation, NMS, box encoding, the one-stage grid idea. Here they go back together into a detector you train yourself, on a CPU, in about twenty seconds: a YOLOv1-like network with an grid on the course's 64 x 64 generated scenes, predicting for every cell "is there an object centre here", its box and its class. It is small enough that every line is visible, and it is evaluated exactly like a real detector, on held-out scenes with AP. It also beats the hand-made detector on the very same 200 test scenes, and the error analysis shows why.
The targets
The model's output is a tensor: for every cell of 8 x 8 pixels, 8 numbers.
| Channel | Meaning | Target | Prediction |
|---|---|---|---|
| 0 | objectness: an object centre lies in this cell | 1 or 0 | logit, |
| 1, 2 | centre offset inside the cell, , | in | |
| 3, 4 | width and height divided by the image size 64 | 0.19 to 0.38 here | |
| 5, 6, 7 | class logits: square, circle, triangle | class index | softmax |
Only the cell that holds an object's centre gets objectness 1 (YOLOv1's responsibility rule), and box and class losses are computed only there. The encode must be exactly invertible, so the first example checks it on 1,000 scenes before any training:
import numpy as np
import numpy as np, cv2
CLASSES = ["square", "circle", "triangle"]
def make_scene(rng, size=64, max_objects=3):
"""Noisy grey background with 1..max_objects shapes that do not touch.
Returns RGB uint8 image, boxes (n, 4) as [x1, y1, x2, y2] with x2, y2 exclusive,
labels (n,) indices into CLASSES, masks (n, size, size) bool."""
img = rng.normal(110, 12, (size, size, 3)).clip(0, 255).astype(np.uint8)
n = int(rng.integers(1, max_objects + 1))
boxes, labels, masks = [], [], []
for _ in range(100):
if len(boxes) == n:
break
s = int(rng.integers(12, 25)); x = int(rng.integers(0, size - s)); y = int(rng.integers(0, size - s))
if any(x < b[2] + 2 and b[0] < x + s + 2 and y < b[3] + 2 and b[1] < y + s + 2 for b in boxes):
continue
c = int(rng.integers(0, 3)); m = np.zeros((size, size), np.uint8)
if c == 0:
cv2.rectangle(m, (x, y), (x + s - 1, y + s - 1), 1, -1)
elif c == 1:
cv2.circle(m, (x + s // 2, y + s // 2), s // 2, 1, -1)
else:
cv2.fillPoly(m, [np.array([[x + s // 2, y], [x, y + s - 1], [x + s - 1, y + s - 1]], np.int32)], 1)
img[m > 0] = rng.integers(0, 256, 3)
ys, xs = np.nonzero(m)
boxes.append([int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1])
labels.append(c); masks.append(m > 0)
return img, np.array(boxes).reshape(-1, 4), np.array(labels), np.array(masks)
G, CELL = 8, 8
def encode(boxes, labels):
T = np.zeros((6, G, G), np.float32) # obj, tx, ty, tw, th, class
for (x1, y1, x2, y2), l in zip(boxes, labels):
cx, cy = (x1 + x2) / 2, (y1 + y2) / 2
j, i = int(cx // CELL), int(cy // CELL)
T[:, i, j] = [1, cx / CELL - j, cy / CELL - i, (x2 - x1) / 64, (y2 - y1) / 64, l]
return T
def decode(T):
out = []
for i, j in zip(*np.nonzero(T[0] > 0.5)):
cx, cy = (j + T[1, i, j]) * CELL, (i + T[2, i, j]) * CELL
w, h = T[3, i, j] * 64, T[4, i, j] * 64
out.append(([cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2], int(T[5, i, j])))
return out
rng = np.random.default_rng(0)
for _ in range(2):
img, boxes, labels, _ = make_scene(rng)
T = encode(boxes, labels)
print("scene 1:", boxes.tolist(), [CLASSES[l] for l in labels])
for i, j in zip(*np.nonzero(T[0])):
print(f" cell row {i}, col {j}: target {[round(float(v), 3) for v in T[1:, i, j]]}")
print(" decoded:", [([round(float(v), 3) for v in b], CLASSES[c]) for b, c in decode(T)])
rng = np.random.default_rng(1)
n_obj, worst, positives = 0, 0.0, 0
for _ in range(1000):
img, boxes, labels, _ = make_scene(rng)
T = encode(boxes, labels)
dec = sorted(decode(T), key=lambda d: d[0][0]); ref = sorted(zip(boxes.tolist(), labels.tolist()))
n_obj += len(boxes); positives += int(T[0].sum())
worst = max([worst] + [float(np.abs(np.array(b) - np.array(r)).max()) for (b, _), (r, _) in zip(dec, ref)])
print(f"1000 scenes: {n_obj} objects, {positives} positive cells, max round-trip error {worst:.1e} px")
print(f"positive cells: {positives / (1000 * G * G):.1%} of all cells")scene 1: [[28, 1, 41, 14], [49, 8, 63, 22]] ['circle', 'square']
cell row 0, col 4: target [0.312, 0.938, 0.203, 0.203, 1.0]
cell row 1, col 7: target [0.0, 0.875, 0.219, 0.219, 0.0]
decoded: [([28.0, 1.0, 41.0, 14.0], 'circle'), ([49.0, 8.0, 63.0, 22.0], 'square')]
1000 scenes: 2033 objects, 2033 positive cells, max round-trip error 0.0e+00 px
positive cells: 3.2% of all cells
The circle in scene 1 has its centre at (34.5, 7.5), so cell row 0, column 4 is responsible, with offsets 0.312 and 0.938 inside the cell and size . Decoding gives back the boxes exactly, on all 2,033 objects of 1,000 scenes (2,033 objects, 2,033 positive cells: no two centres ever share a cell in these scenes, as counted earlier). Only 3.2% of the cells are positive, the class imbalance every detector has.
Training
The network is four convolution blocks (convolution, batch norm, ReLU), three of them followed by max pooling, so a 64 x 64 input becomes an 8 x 8 map, and a convolution to the 8 output channels (CNN from scratch explains the layers). The loss is the sum of three parts, each summed over cells and averaged over images:
The weight 5 on the box term follows YOLOv1's idea of up-weighting localisation; the box and class terms are computed only where an object is, so the 97% empty cells teach only objectness. Data: 1,500 generated training scenes (seed 0), 300 validation scenes (seed 2) to watch the loss, and as test set the same 200 scenes (seed 1) the hand-made detector was scored on. Adam, learning rate 0.003, batch 64, 12 epochs. After training, decoding takes every cell with score , then class-aware NMS at IoU 0.5, and AP is computed as in detection metrics (VOC all-point, per class). PyTorch cannot run in the browser, so this example is recorded (CPU, in Docker):
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np, cv2
CLASSES = ["square", "circle", "triangle"]
def make_scene(rng, size=64, max_objects=3):
"""Noisy grey background with 1..max_objects shapes that do not touch.
Returns RGB uint8 image, boxes (n, 4) as [x1, y1, x2, y2] with x2, y2 exclusive,
labels (n,) indices into CLASSES, masks (n, size, size) bool."""
img = rng.normal(110, 12, (size, size, 3)).clip(0, 255).astype(np.uint8)
n = int(rng.integers(1, max_objects + 1))
boxes, labels, masks = [], [], []
for _ in range(100):
if len(boxes) == n:
break
s = int(rng.integers(12, 25)); x = int(rng.integers(0, size - s)); y = int(rng.integers(0, size - s))
if any(x < b[2] + 2 and b[0] < x + s + 2 and y < b[3] + 2 and b[1] < y + s + 2 for b in boxes):
continue
c = int(rng.integers(0, 3)); m = np.zeros((size, size), np.uint8)
if c == 0:
cv2.rectangle(m, (x, y), (x + s - 1, y + s - 1), 1, -1)
elif c == 1:
cv2.circle(m, (x + s // 2, y + s // 2), s // 2, 1, -1)
else:
cv2.fillPoly(m, [np.array([[x + s // 2, y], [x, y + s - 1], [x + s - 1, y + s - 1]], np.int32)], 1)
img[m > 0] = rng.integers(0, 256, 3)
ys, xs = np.nonzero(m)
boxes.append([int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1])
labels.append(c); masks.append(m > 0)
return img, np.array(boxes).reshape(-1, 4), np.array(labels), np.array(masks)
torch.manual_seed(0)
G, CELL = 8, 8
def dataset(seed, n):
rng = np.random.default_rng(seed)
X = np.zeros((n, 3, 64, 64), np.float32); T = np.zeros((n, 6, G, G), np.float32); truth = []
for k in range(n):
img, boxes, labels, _ = make_scene(rng)
X[k] = img.transpose(2, 0, 1) / 255.0
for (x1, y1, x2, y2), l in zip(boxes, labels):
cx, cy = (x1 + x2) / 2, (y1 + y2) / 2
j, i = int(cx // CELL), int(cy // CELL)
T[k, :, i, j] = [1, cx / CELL - j, cy / CELL - i, (x2 - x1) / 64, (y2 - y1) / 64, l]
truth.append((boxes, labels))
return torch.tensor(X), torch.tensor(T), truth
Xtr, Ttr, _ = dataset(0, 1500)
Xva, Tva, _ = dataset(2, 300)
Xte, Tte, test = dataset(1, 200) # the hand-made detector's 200 test scenes
def block(i, o):
return nn.Sequential(nn.Conv2d(i, o, 3, padding=1), nn.BatchNorm2d(o), nn.ReLU())
net = nn.Sequential(block(3, 16), nn.MaxPool2d(2), block(16, 32), nn.MaxPool2d(2), block(32, 64), nn.MaxPool2d(2),
block(64, 64), nn.Conv2d(64, 8, 1))
print("parameters:", sum(p.numel() for p in net.parameters()))
def losses(out, T):
pos = T[:, 0] > 0
l_obj = F.binary_cross_entropy_with_logits(out[:, 0], T[:, 0], reduction="sum") / len(out)
o, t = out.permute(0, 2, 3, 1)[pos], T.permute(0, 2, 3, 1)[pos]
l_box = F.l1_loss(torch.sigmoid(o[:, 1:5]), t[:, 1:5], reduction="sum") / len(out)
l_cls = F.cross_entropy(o[:, 5:], t[:, 5].long(), reduction="sum") / len(out)
return l_obj, l_box, l_cls
opt = torch.optim.Adam(net.parameters(), lr=3e-3)
for epoch in range(1, 13):
net.train()
perm = torch.randperm(len(Xtr))
for k in range(0, len(Xtr), 64):
idx = perm[k:k + 64]
l_obj, l_box, l_cls = losses(net(Xtr[idx]), Ttr[idx])
loss = l_obj + 5 * l_box + l_cls
opt.zero_grad(); loss.backward(); opt.step()
if epoch % 3 == 0:
net.eval()
with torch.no_grad():
l_obj, l_box, l_cls = losses(net(Xva), Tva)
print(f"epoch {epoch:2d} validation loss: objectness {l_obj.item():.3f} box {l_box.item():.3f} class {l_cls.item():.3f}")
def decode(out, conf=0.05):
obj = torch.sigmoid(out[0]); prob = torch.softmax(out[5:], 0); txy = torch.sigmoid(out[1:5])
score = obj * prob.max(0).values
dets = []
for i, j in zip(*torch.nonzero(score > conf, as_tuple=True)):
cx, cy = (j + txy[0, i, j]) * CELL, (i + txy[1, i, j]) * CELL
w, h = txy[2, i, j] * 64, txy[3, i, j] * 64
dets.append((int(prob[:, i, j].argmax()), float(score[i, j]), [float(cx - w / 2), float(cy - h / 2), float(cx + w / 2), float(cy + h / 2)]))
return dets
def iou(a, b):
iw = max(0.0, min(a[2], b[2]) - max(a[0], b[0])); ih = max(0.0, min(a[3], b[3]) - max(a[1], b[1]))
return iw * ih / ((a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - iw * ih)
def nms(dets, thr=0.5):
keep = []
for d in sorted(dets, key=lambda d: -d[1]):
if all(k[0] != d[0] or iou(k[2], d[2]) <= thr for k in keep): # class-aware
keep.append(d)
return keep
def ap(per_image, truth, cls, thr):
g = [(n, b.tolist()) for n, (bx, lb) in enumerate(truth) for b, l in zip(bx, lb) if l == cls]
rows = sorted([(n, s, b) for n, d in enumerate(per_image) for c, s, b in d if c == cls], key=lambda r: -r[1])
used, tp = set(), []
for n, s, b in rows:
best, j = max([(iou(b, gb), j) for j, (gn, gb) in enumerate(g) if gn == n], default=(0.0, -1))
tp.append(best >= thr and j not in used); used |= {j} if tp[-1] else set()
tp = np.array(tp, float)
prec, rec = np.cumsum(tp) / np.arange(1, len(tp) + 1), np.cumsum(tp) / len(g)
return float(np.sum(np.diff(np.r_[0, rec]) * np.maximum.accumulate(prec[::-1])[::-1]))
net.eval()
with torch.no_grad():
out = net(Xte)
raw = [decode(o) for o in out]
final = [nms(d) for d in raw]
for name, per_image in [("without NMS", raw), ("with NMS", final)]:
for thr in [0.5, 0.75]:
aps = [ap(per_image, test, c, thr) for c in range(3)]
print(f"test, {name:11s} AP@{thr}: " + " ".join(f"{CLASSES[c]} {a:.3f}" for c, a in enumerate(aps)) + f" | mAP {np.mean(aps):.3f}")
found = wrong = missed = loose = fp = 0
for (bx, lb), d in zip(test, final):
d = [x for x in d if x[1] > 0.5] # the operating point: score > 0.5
matched = set()
for b, l in zip(bx.tolist(), lb.tolist()):
ious = [iou(b, x[2]) for x in d]
k = int(np.argmax(ious)) if ious else -1
if k < 0 or ious[k] < 0.5:
missed += 1; continue
matched.add(k)
if d[k][0] != l: wrong += 1
else: found += 1; loose += int(ious[k] < 0.75)
fp += len(d) - len(matched)
print(f"at score > 0.5: correct {found} (of which IoU < 0.75: {loose}), wrong class {wrong}, missed {missed}, false positives {fp}")
# What it cannot do: the same model on test images unlike the training data
def make_scene_sized(rng, smin, smax, size=64):
"""Variant of make_scene for this test only: object sizes smin..smax-1 instead of 12..24, at most 2 objects."""
img = rng.normal(110, 12, (size, size, 3)).clip(0, 255).astype(np.uint8)
boxes, labels = [], []
n = int(rng.integers(1, 3))
for _ in range(100):
if len(boxes) == n:
break
s = int(rng.integers(smin, smax)); x = int(rng.integers(0, size - s)); y = int(rng.integers(0, size - s))
if any(x < b[2] + 2 and b[0] < x + s + 2 and y < b[3] + 2 and b[1] < y + s + 2 for b in boxes):
continue
c = int(rng.integers(0, 3)); m = np.zeros((size, size), np.uint8)
if c == 0:
cv2.rectangle(m, (x, y), (x + s - 1, y + s - 1), 1, -1)
elif c == 1:
cv2.circle(m, (x + s // 2, y + s // 2), s // 2, 1, -1)
else:
cv2.fillPoly(m, [np.array([[x + s // 2, y], [x, y + s - 1], [x + s - 1, y + s - 1]], np.int32)], 1)
img[m > 0] = rng.integers(0, 256, 3)
ys, xs = np.nonzero(m)
boxes.append([int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1]); labels.append(c)
return img, np.array(boxes).reshape(-1, 4), np.array(labels)
def map50(X, truth):
with torch.no_grad():
dets = [nms(decode(o)) for o in net(X)]
return np.mean([ap(dets, truth, c, 0.5) for c in range(3)])
g = torch.Generator().manual_seed(0)
rng = np.random.default_rng(3)
big = [make_scene_sized(rng, 30, 41) for _ in range(200)]
Xbig = torch.tensor(np.stack([im.transpose(2, 0, 1) / 255.0 for im, _, _ in big]), dtype=torch.float32)
print("mAP@0.5 on the 200 test scenes:")
print(f" as trained {map50(Xte, test):.3f}")
print(f" brighter (+60 grey levels) {map50((Xte + 60 / 255).clamp(0, 1), test):.3f}")
print(f" noisier (+ noise, sigma 25) {map50((Xte + torch.randn(Xte.shape, generator=g) * 25 / 255).clamp(0, 1), test):.3f}")
print(f" larger objects (30 to 40 px) {map50(Xbig, [(b, l) for _, b, l in big]):.3f}")parameters: 61384
epoch 3 validation loss: objectness 3.026 box 0.350 class 0.753
epoch 6 validation loss: objectness 1.419 box 0.214 class 0.196
epoch 9 validation loss: objectness 1.010 box 0.216 class 0.096
epoch 12 validation loss: objectness 0.759 box 0.182 class 0.078
test, without NMS AP@0.5: square 0.993 circle 0.980 triangle 0.995 | mAP 0.990
test, without NMS AP@0.75: square 0.987 circle 0.977 triangle 0.957 | mAP 0.974
test, with NMS AP@0.5: square 1.000 circle 0.984 triangle 1.000 | mAP 0.995
test, with NMS AP@0.75: square 0.991 circle 0.975 triangle 0.942 | mAP 0.969
at score > 0.5: correct 369 (of which IoU < 0.75: 4), wrong class 1, missed 34, false positives 0
mAP@0.5 on the 200 test scenes:
as trained 0.995
brighter (+60 grey levels) 0.059
noisier (+ noise, sigma 25) 0.796
larger objects (30 to 40 px) 0.185
Reading the results
Training. The model has 61,384 parameters. All three validation losses fall over the 12 epochs; the objectness loss is still falling at the end (0.759), so more epochs would help, but the point here is a run of about twenty seconds on a CPU.
Accuracy. On the 200 test scenes (404 objects) the trained detector reaches mAP 0.995 at IoU 0.5 and 0.969 at IoU 0.75. The hand-made detector of detection basics scored 0.767 and 0.748 on exactly these scenes. The difference is where that detector failed: it missed 19 low-contrast objects and gave 40 objects the wrong class, while the trained network, at score above 0.5, gives only 1 wrong class and no false positives. It learned the shape differences that the fill-ratio rule could not express.
NMS. Without NMS the mAP is already 0.990: one cell per object means few duplicates, and neighbouring cells rarely fire. NMS still helps at IoU 0.5 (0.995). At IoU 0.75 it costs a little (0.974 to 0.969), because it sometimes keeps the higher-scoring of two boxes when the lower-scoring one was tighter. Differences of this size on 404 objects are within noise.
AP versus the operating point. At a score threshold of 0.5 the detector misses 34 objects although its AP is almost perfect. AP only needs the right ranking: those 34 objects have scores below 0.5 but above every false detection. The scores are not calibrated yet (the objectness loss was still falling), so the threshold for deployment must be chosen on the validation scenes, never fixed at 0.5 by habit.
What it cannot do. The last four lines evaluate the same model on test images that differ from the training data:
- Brighter images (+60 grey levels): mAP 0.059. Every training background was grey around 110; the model learned "not 110-ish grey means object" and now sees objects everywhere or nowhere. Brightness augmentation during training is the fix.
- More noise (an extra ): 0.796. Degraded but working: noise was present in training, only weaker.
- Larger objects (30 to 40 pixels, never seen in training): 0.185. The network has never predicted a width above , and a 40-pixel object spans several cells. Real detectors handle scale with multi-scale training data and feature pyramids.
Beyond that, by construction it predicts at most one object per 8 x 8 cell, only three classes, only at 64 x 64 input, and was trained on synthetic shapes with exact labels. Its numbers say how well it fits this generator, nothing about real images (distribution shift, robustness testing).
From this to a real detector
| This lesson | A YOLOv8-class detector |
|---|---|
| 4 conv blocks, 61 thousand parameters | CSP backbone + feature pyramid neck, 3 to 68 million parameters |
| one grid, stride 8 | three levels, strides 8, 16, 32 |
| objectness + 4 box numbers + softmax classes | anchor-free: DFL distances + sigmoid classes, no objectness |
| centre cell is responsible | task-aligned assigner, top 10 points per object |
| L1 box loss | CIoU + DFL losses |
| 1,500 synthetic images, 12 epochs | COCO (118 thousand images), hundreds of epochs, mosaic and colour augmentation |
Every row is a refinement of the same structure: candidates on a grid, an objectness or class score, a box regression, NMS, AP. The next lesson uses the real thing.
Pitfalls
- Box loss on empty cells. The box and class losses must be masked to positive cells; computing them everywhere trains every cell to predict a box of zeros.
- Objectness swamped by negatives. With 97% negative cells, an unweighted mean BCE lets the model predict "nothing" everywhere and still look good. Summing per image (as here), weighting positives or using focal loss keeps the positives visible.
- Evaluating on the training generator's seed. Train, validation and test scenes come from different seeds here; the same scenes in train and test would overstate the result.
- A fixed 0.5 score threshold. AP was 0.995 and recall at 0.5 was only 91% (369 of 404). Choose the threshold on validation data.
- Believing a synthetic score. 0.995 on generated shapes says nothing about photos. The robustness lines are the honest part of the evaluation.
Practice
- With an grid and objects of 12 to 24 pixels that never touch, why can two objects never share a cell, and what changes for objects allowed to overlap?
Answer
Two shapes at least 12 pixels wide with a 2-pixel gap have centres at least 14 pixels apart in or , more than a cell (8 pixels). With overlapping objects, centres can be arbitrarily close; one of them would be lost by a one-object-per-cell model. Anchors or several predictors per cell, or finer grids, fix that.
- How would you make the detector robust to the brightness change that dropped mAP to 0.059? How would you check that the fix works without fooling yourself?
Answer
Train with brightness and contrast augmentation (random offsets of, say, grey levels and gains), or normalise each image (subtract its median). Check on a test set with brightness shifts that was not used for choosing the augmentation, and report the clean test mAP too, to make sure it did not get worse.
- At score above 0.5 the detector found 369 objects correctly. Compute precision and recall at that threshold.
Answer
Detections above 0.5: 369 correct + 1 wrong class + 0 false positives = 370; the wrong-class one is a false positive for its predicted class and a miss for the true one. Precision , recall .
Test yourself
In the tiny detector, which cells receive a box and class loss?
- All 64 cells
- Only the cell that contains an object's centre
- The cells the box overlaps
- Cells with predicted objectness above 0.5
The detector has AP@0.5 of 0.995 but misses 34 of 404 objects at score above 0.5. How is that possible?
- AP is computed on the training set
- AP depends on the ranking of scores; those objects have low but still higher scores than any false detection
- NMS removed them
- AP ignores missed objects
Why did mAP fall from 0.995 to 0.059 when the test images were made 60 grey levels brighter?
- The images became too large
- All training backgrounds had the same grey level, so the model learned a shortcut that breaks under a brightness shift
- NMS fails on bright images
- The learning rate was too high