Driving by Imitation: Camera to Steering
Skip lanes and boxes entirely: train a network that maps the camera image straight to a steering angle by copying a driver (behaviour cloning, as in NVIDIA's PilotNet). See why a low test error is not enough, why the car drifts off the road, and how recovery data fixes it.
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
Learning to drive by copying: show a network thousands of pictures of the road, each with the steering angle a good driver used, and it learns to steer by itself. The catch: if it only ever saw perfect driving, it has no idea how to recover from its own small mistakes.
By the end of this topic you will be able to explain end-to-end driving, and why a network must also see recoveries.
Start with: the demo Try it: let the network drive.
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.
End to end
So far the car has a modular pipeline: perception finds lanes and objects, then a controller decides. End-to-end driving replaces the chain with one network: image in, steering out. It learns by copying a driver: behaviour cloning, a form of imitation learning.
The idea is old (ALVINN drove a van with a tiny network in 1989) and was made famous by NVIDIA's PilotNet (Bojarski et al., 2016), which learned to steer on real roads from about 70 hours of human driving. Today several companies train large end-to-end driving models.
The trade-off: end-to-end needs no hand-made labels beyond what the driver did, and it can learn cues nobody thought to label. But it is hard to inspect ("why did it steer left?") and hard to test piece by piece, which matters for safety.
The trap: copying is not driving
Train on a perfect driver and the network sees only images of a car in the middle of its lane. Then it drives, makes one small error, and sees an image it has never seen: the car slightly off centre. It has no idea how to recover, makes a bigger error, and drifts off the road. Errors compound: this is called distribution shift or covariate shift.
A low test error does not catch this, because the test set comes from the same perfect driving. The only real test is closed loop: let the network drive.
Fixes:
- Recovery data: record the expert driving with deliberate wobbles, and label each frame with what the expert does to get back to the centre. The recorder's steering wobbles option does exactly this: the car drifts, but the label is always the clean correction.
- Side cameras: PilotNet used left and right cameras, labelled with a corrected steering angle, as if the car were off centre.
- DAgger (Ross et al., 2011): let the network drive, ask the expert what it should have done in the states the network reached, add those, retrain.
On our tracks, a network trained only on clean driving left the road at the City S-bend. Trained with wobble recordings, it laps every track day and night, even though its offline test error got slightly worse. Offline scores and driving ability are not the same thing.
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: load the data
Record four or more datasets with steering wobbles on, on all tracks and in mixed weather. Driving with wobbles labels each frame with the clean correction.
# In Google Colab. Upload several recordings made with steering wobbles on (the last is kept for testing).
from google.colab import files
import numpy as np
names = list(files.upload())
assert len(names) >= 2, "Upload at least two recordings: the last one is kept for testing."
H, W = 64, 128
rows = ((np.arange(H) + 0.5) * 120 / H).astype(int)
cols = ((np.arange(W) + 0.5) * 240 / W).astype(int)
def load(name):
d = np.load(name)
return d["images"][:, rows][:, :, cols], d["steer"].astype(np.float32), d["weather"]
data = [load(n) for n in names]
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 frames:", len(X_train), "| steering spread (std):", y_train.std().round(3), "rad")
print("error if we always predict the average steering:", np.abs(y_test - y_train.mean()).mean().round(4), "rad")Code: the network and training
Note the Flatten instead of global average pooling: steering depends on where the road is in the image, and averaging would throw that away.
import torch
import torch.nn as nn
device = "cuda" if torch.cuda.is_available() else "cpu"
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)
raw = lambda X: torch.tensor(X, dtype=torch.float32, device=device).permute(0, 3, 1, 2) / 255
SCALE = 4.0 # steering is small (about ±0.3 rad), so the network predicts 4 × steer
pilot = nn.Sequential( # in the spirit of NVIDIA's PilotNet, smaller
nn.Conv2d(3, 24, 5, 2, 2), nn.ReLU(), # 32 × 64
nn.Conv2d(24, 32, 5, 2, 2), nn.ReLU(), # 16 × 32
nn.Conv2d(32, 48, 3, 2, 1), nn.ReLU(), # 8 × 16
nn.Conv2d(48, 64, 3, 1, 1), nn.ReLU(),
nn.Conv2d(64, 64, 3, 2, 1), nn.ReLU(), # 4 × 8
nn.Flatten(), # keep where things are: steering depends on position
nn.Linear(64 * 4 * 8, 32), nn.ReLU(),
nn.Linear(32, 1),
).to(device)
opt = torch.optim.AdamW(pilot.parameters(), lr=1e-3, weight_decay=1e-4)
sched = torch.optim.lr_scheduler.StepLR(opt, step_size=8, gamma=0.5)
y_t = torch.tensor(y_train, device=device)
for epoch in range(16):
pilot.train()
perm = torch.randperm(len(X_train)).numpy()
for i in range(0, len(perm), 32):
b = perm[i:i + 32]
r = (raw(X_train[b]) * torch.empty(len(b), 1, 1, 1, device=device).uniform_(0.7, 1.3)).clamp(0, 1)
loss = ((pilot((r - m) / s)[:, 0] - SCALE * y_t[b]) ** 2).mean()
opt.zero_grad()
loss.backward()
opt.step()
sched.step()
pilot.eval()
with torch.no_grad():
pred = np.concatenate([pilot((raw(X_test[i:i + 100]) - m) / s)[:, 0].cpu().numpy() for i in range(0, len(X_test), 100)]) / SCALE
print(f"epoch {epoch + 1}: test error {np.abs(pred - y_test).mean():.4f} rad")Code: export
Paste the export helpers from the detection topic into this notebook first.
from google.colab import files
pilot = pilot.eval().cpu()
save_model(layers_of(pilot), "pilot.json", "steering", ["steer"], H, W, mean, std, scale=SCALE)
files.download("pilot.json")Try it: let the network drive
The network sees only the camera and outputs the steering angle; speed comes from the simulator's speed planner. The chart compares its steering with what the autopilot would have done. Try every track and the night; then load your own model, trained with and without wobbles, and compare.
Interactive: this part runs in your browser.
Quiz
1. Why does a network trained only on perfect driving drift off the road?
2. What does the wobble option in the recorder add to the data?
3. Which is the real test of a driving network?
4. Why use Flatten rather than global average pooling here?
📚 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.
- Bojarski et al. (2016): End to End Learning for Self-Driving Cars ↗ NVIDIA's PilotNet, camera to steering
- Ross, Gordon & Bagnell (2011): A Reduction of Imitation Learning and Structured Prediction to No-Regret Online Learning (DAgger) ↗ why behaviour cloning drifts, and a fix