Traffic-Light Classifier: Your First CNN from Scratch
Build the perception step that reads traffic lights: crop each light from your recorded data, design a small convolutional network, train it from scratch in PyTorch with class weights and augmentation, check it by weather, export it, and load it into the simulator so the car stops at red lights using your network.
Softmaxima Simulator StudioTry this topic's code in the Studio: it opens with the camera and trained networks project, ready to run.OpenIn plain words
A traffic light has three lamps; which one is lit tells you red, amber or green. A small neural network can learn to tell them apart from examples, even at night, even when a rule like "is the top lamp brightest?" gets it wrong.
By the end of this topic you will be able to explain how a small CNN learns from examples, and watch one read the lights while the car drives.
Start with: the demo Try it: your network reads the lights and drives.
You do not need to train anything to follow this topic. Every demo comes with an example network that already works. Training your own in Google Colab (the Code sections) is an optional level-up you can do now or later.
Where this fits
Reading a traffic light is a two-step job in most self-driving systems: first find the light in the image (object detection, a later topic), then classify a small crop of it. Classifying a crop is a simpler, faster task than reading the whole scene, so a tiny network can do it reliably and many times a second. In this topic the boxes come from the simulator's labels, so you can focus on the classifier; after the detection topic, your own detector will provide them.
Real traffic lights are harder than ours: lights with arrows, lights for other lanes, LEDs that flicker in camera images, sun behind the light, and lights far away that are only a few pixels tall. The method is the same; real systems need much more varied data.
Step 1: record the data
In Recording a labelled dataset, tick Only frames with a traffic light ahead, choose all four kinds of weather, and record at least three files, on different tracks. Each 300-frame recording gives roughly 150–200 usable crops. Amber is on for only 2 seconds in every 18, so it will be the rarest class: that is realistic, and the training code handles it.
Each box in the dataset carries the light's own colour (state), so every crop has an exact label. Lights seen from behind, across the middle of the track, show no colour and have state 0; the code skips them, along with lights too small to read or cut off by the edge of the image.
Going deeper
The sections marked Intermediate · Maths, Code or Advanced go deeper: the equations, the code and the finer details. They are worth it when you are ready, but you can follow the whole idea without them. To hide them, press those buttons next to Show at the top of the page; the Beginner explanations and Try it demos stay.
Code: crop the lights
Run this first in a new Colab notebook. It cuts each light out with a small margin and resizes it to 24 × 12 pixels, exactly as the simulator will when it runs your model later.
# In Google Colab. Upload two or more recordings made with "Only frames with a traffic light ahead".
from google.colab import files
import numpy as np
names = list(files.upload()) # choose several .npz files at once
assert len(names) >= 2, "Upload at least two recordings: the last one is kept for testing."
CLASSES = ["red", "amber", "green"]
CROP_H, CROP_W = 24, 12 # every crop is resized to 24 × 12 pixels
def crop_lights(path):
"""Cut out every visible traffic light, with its state as the label."""
d = np.load(path)
imgs, boxes, weather = d["images"], d["boxes"], d["weather"]
X, y, w = [], [], []
for frame, cls, x1, y1, x2, y2, state in boxes:
if cls != 2 or state == 0: # class 2 = traffic light; state 0 = seen from behind
continue
bw, bh = x2 - x1, y2 - y1
if bh < 6: # too far away to read
continue
if x1 == 0 or y1 == 0 or x2 >= imgs.shape[2] or y2 >= imgs.shape[1]:
continue # cut off by the edge of the image
px, py = max(1, bw // 4), max(1, bh // 8) # a little margin round the box
x1, x2 = max(0, x1 - px), min(imgs.shape[2], x2 + px)
y1, y2 = max(0, y1 - py), min(imgs.shape[1], y2 + py)
rows = (y1 + (np.arange(CROP_H) + 0.5) * (y2 - y1) / CROP_H).astype(int) # nearest-pixel resize,
cols = (x1 + (np.arange(CROP_W) + 0.5) * (x2 - x1) / CROP_W).astype(int) # the same as the simulator uses
X.append(imgs[frame][rows][:, cols])
y.append(state - 1) # the light's own state: 1 red, 2 amber, 3 green -> 0, 1, 2
w.append(weather[frame])
return np.array(X), np.array(y, dtype=np.int64), np.array(w)
data = [crop_lights(n) for n in names]
# Test on a whole recording the model never trains on, so neighbouring frames cannot leak between the two sets
X_train = np.concatenate([d[0] for d in data[:-1]])
y_train = np.concatenate([d[1] for d in data[:-1]])
X_test, y_test, w_test = data[-1]
print("training crops:", len(y_train), "per class", dict(zip(CLASSES, np.bincount(y_train, minlength=3).tolist())))
print("test crops: ", len(y_test), "per class", dict(zip(CLASSES, np.bincount(y_test, minlength=3).tolist())))Designing the network
The network is a small convolutional neural network (see Convolutional networks in depth):
- Convolution layers slide small 3 × 3 filters over the crop. The first layer learns simple patterns such as "a bright red patch" or "an edge"; later layers combine them into "a lit lamp at the top".
- Max pooling halves the height and width, so later filters see a larger part of the light. After two poolings, each value summarises a quarter of the crop.
- Batch normalisation keeps each layer's values in a steady range, which makes training faster and less sensitive to the learning rate.
- Global average pooling turns the last feature maps into 32 numbers, and a linear layer turns those into three scores. Softmax makes the scores probabilities, and cross-entropy is the loss.
The whole network has about 15,000 parameters, tiny by modern standards, because the task is narrow. Two training tricks matter more than size here:
- Class weights: amber is rare, so each amber mistake costs more in the loss. Otherwise the network can score well while rarely predicting amber.
- Data augmentation: each time a crop is used, it is made randomly brighter or darker and shifted by a pixel. The network sees endless slightly different versions and learns that the position and colour of the lit lamp matter, not the exact brightness.
Code: build and train the CNN from scratch
Use a GPU if you like (Runtime → Change runtime type), but this network trains in under a minute even on Colab's CPU.
import torch
import torch.nn as nn
device = "cuda" if torch.cuda.is_available() else "cpu"
# Normalise each colour channel with the training set's mean and spread
mean = X_train.reshape(-1, 3).mean(0) / 255
std = X_train.reshape(-1, 3).std(0) / 255
m = torch.tensor(mean, dtype=torch.float32, device=device).view(1, 3, 1, 1)
s = torch.tensor(std, dtype=torch.float32, device=device).view(1, 3, 1, 1)
def raw(X): # (N, H, W, 3) uint8 -> (N, 3, H, W) floats in 0..1
return torch.tensor(X, dtype=torch.float32, device=device).permute(0, 3, 1, 2) / 255
def norm(r):
return (r - m) / s
def augment(r):
r = r * torch.empty(len(r), 1, 1, 1, device=device).uniform_(0.6, 1.4) # brighter or darker
r = torch.roll(r, shifts=int(torch.randint(-1, 2, (1,))), dims=2) # move up or down a pixel
return r.clamp(0, 1)
model = nn.Sequential(
nn.Conv2d(3, 16, 3, padding=1), nn.BatchNorm2d(16), nn.ReLU(), nn.MaxPool2d(2), # 24×12 -> 12×6
nn.Conv2d(16, 32, 3, padding=1), nn.BatchNorm2d(32), nn.ReLU(), nn.MaxPool2d(2), # 12×6 -> 6×3
nn.Conv2d(32, 32, 3, padding=1), nn.ReLU(),
nn.AdaptiveAvgPool2d(1), nn.Flatten(), # 32 numbers
nn.Dropout(0.2), nn.Linear(32, 3), # 3 scores: red, amber, green
).to(device)
print(sum(p.numel() for p in model.parameters()), "parameters")
# Amber is rare, so mistakes on amber count for more
counts = np.bincount(y_train, minlength=3)
weights = torch.tensor(len(y_train) / (3 * np.maximum(counts, 1)), dtype=torch.float32, device=device)
loss_fn = nn.CrossEntropyLoss(weight=weights)
opt = torch.optim.AdamW(model.parameters(), lr=3e-3, weight_decay=1e-4)
R_train, y_tr = raw(X_train), torch.tensor(y_train, device=device)
R_test, y_te = raw(X_test), torch.tensor(y_test, device=device)
for epoch in range(40):
model.train()
perm = torch.randperm(len(y_tr), device=device)
for i in range(0, len(perm), 32):
b = perm[i:i + 32]
loss = loss_fn(model(norm(augment(R_train[b]))), y_tr[b])
opt.zero_grad()
loss.backward()
opt.step()
if epoch % 10 == 9:
model.eval()
with torch.no_grad():
acc = (model(norm(R_test)).argmax(1) == y_te).float().mean().item()
print(f"epoch {epoch + 1}: training loss {loss.item():.3f}, test accuracy {acc:.1%}")Code: check it properly
Accuracy alone hides which mistakes happen. A red light read as green is far worse than a green read as amber, so look at the confusion matrix, and at accuracy in each kind of weather.
import torch
model.eval()
with torch.no_grad():
pred = model(norm(R_test)).argmax(1).cpu().numpy()
confusion = np.zeros((3, 3), dtype=int)
for t, p in zip(y_test, pred):
confusion[t, p] += 1
print("rows = true colour, columns = predicted (red, amber, green)")
print(confusion)
print("most dangerous mistake, a red light read as green:", confusion[0, 2])
for k, name in enumerate(["day", "dusk", "night", "rain"]):
sel = w_test == k
if sel.any():
print(f"{name:>5}: {(pred[sel] == y_test[sel]).mean():.1%} correct of {sel.sum()} lights")Code: export your model for the simulator
This saves the trained network as a small JSON file the simulator can run in your browser, and downloads it.
import json
import base64
import torch
import torch.nn as nn
def export_softmaxima(model, path, task, classes, in_h, in_w, mean, std):
"""Save a trained nn.Sequential in the format the Softmaxima simulator runs.
Batch normalisation is folded into the convolution before it, which gives the same output in eval mode."""
model = model.eval().cpu()
f32 = lambda t: base64.b64encode(t.detach().numpy().astype("<f4").tobytes()).decode()
mods = [m for m in model.modules() if not isinstance(m, nn.Sequential)]
layers, i = [], 0
while i < len(mods):
m = mods[i]
if isinstance(m, nn.Conv2d):
w = m.weight.detach().clone()
b = m.bias.detach().clone() if m.bias is not None else torch.zeros(m.out_channels)
if i + 1 < len(mods) and isinstance(mods[i + 1], nn.BatchNorm2d):
bn = mods[i + 1]
i += 1
scale = bn.weight.detach() / torch.sqrt(bn.running_var + bn.eps)
w = w * scale[:, None, None, None]
b = (b - bn.running_mean) * scale + bn.bias.detach()
layers.append(dict(type="conv", inC=m.in_channels, outC=m.out_channels, k=m.kernel_size[0],
stride=m.stride[0], pad=m.padding[0], w=f32(w), b=f32(b)))
elif isinstance(m, nn.ReLU):
layers.append(dict(type="relu"))
elif isinstance(m, nn.MaxPool2d):
k = m.kernel_size if isinstance(m.kernel_size, int) else m.kernel_size[0]
st = m.stride if isinstance(m.stride, int) else m.stride[0]
layers.append(dict(type="maxpool", k=k, s=st))
elif isinstance(m, nn.AdaptiveAvgPool2d):
layers.append(dict(type="gap"))
elif isinstance(m, nn.Flatten):
layers.append(dict(type="flatten"))
elif isinstance(m, nn.Linear):
layers.append(dict(type="linear", inF=m.in_features, outF=m.out_features, w=f32(m.weight), b=f32(m.bias)))
elif isinstance(m, nn.Dropout):
pass # dropout does nothing once training is over
else:
raise ValueError(f"The simulator cannot run {type(m).__name__} layers yet")
i += 1
spec = dict(format="softmaxima-v1", task=task, classes=classes,
input=dict(h=in_h, w=in_w, mean=[float(v) for v in mean], std=[float(v) for v in std]), layers=layers)
with open(path, "w") as fh:
json.dump(spec, fh)
print(f"saved {path} with {len(layers)} layers")
export_softmaxima(model, "traffic_light_cnn.json", "traffic-light", CLASSES, CROP_H, CROP_W, mean, std)
files.download("traffic_light_cnn.json")Try it: your network reads the lights and drives
The simulator crops every light the camera sees, exactly as your training code did, and runs the network on it in your browser. It starts with an example network trained on simulator data with the same design; press Load your model to use yours. Choose what the car obeys at junctions and watch the red lights run counter, especially at night and in rain. Compare your network with the hand-written rule (brightest third of the light).
Interactive: this part runs in your browser.
What would change in a real car
- More classes: arrows, flashing amber, pedestrian signals, "light is off", and "not a traffic light at all" for false detections.
- Which light is mine? At big junctions, several lights face the car. The system must match lights to lanes, often using the map.
- Time, not single frames: a light does not jump from red to green and back in 0.1 seconds. Smoothing predictions over a few frames removes flickers, and a known red-amber-green order catches impossible changes.
- Safety first: when unsure, assume the light is red and slow down. The cost of each mistake, not the accuracy, should set the decision threshold.
Quiz
1. Why does the training code use class weights?
2. Why is one whole recording kept for testing instead of a random 20% of crops?
3. Which mistake should worry you most?
4. What does randomly changing the brightness of training crops teach the network?
📚 Further reading
Trusted, mostly free sources: official documentation, well-known textbooks and courses. When you want to confirm or go deeper on anything here, start with these.
- Hartley & Zisserman: Multiple View Geometry in Computer Vision ↗ the classic reference on camera models and projection