Lesson 4 of 7 · 2 min
Train the driver
Driving data is mostly "go straight", so the rare turns are weighted up. Split by time, not at random: neighbouring frames are nearly identical and would leak.
# run locally: train.py
import numpy as np, torch, torch.nn as nn
d = np.load("drive.npz")
x = torch.tensor(d["x"]).float().unsqueeze(1) / 255
y = torch.tensor(d["y"]).long()
cut = int(len(x) * 0.85)
net = nn.Sequential(
nn.Conv2d(1, 16, 8, 4), nn.ReLU(), nn.Conv2d(16, 32, 4, 2), nn.ReLU(),
nn.Conv2d(32, 64, 3, 1), nn.ReLU(), nn.Flatten(),
nn.LazyLinear(256), nn.ReLU(), nn.Dropout(0.3), nn.Linear(256, 5))
net(x[:1])
counts = torch.bincount(y[:cut], minlength=5).float()
loss_fn = nn.CrossEntropyLoss(weight=(counts.sum() / (counts + 1)).clamp(max=10))
opt = torch.optim.AdamW(net.parameters(), lr=3e-4)
for epoch in range(12):
net.train()
for batch in torch.randperm(cut).split(64):
opt.zero_grad()
loss_fn(net(x[batch]), y[batch]).backward()
opt.step()
net.eval()
with torch.no_grad():
acc = (net(x[cut:]).argmax(1) == y[cut:]).float().mean()
print(epoch, f"held-out accuracy {acc:.2%}")
torch.save(net, "driver.pt")