AI Learns to Drive
Neural network cars learn to drive through traffic, one generation at a time. No libraries, just JavaScript and canvas.
- JavaScript
- HTML Canvas
- Neural Networks
- No Libraries
Training runs in your browser. The first cars crash almost at once, then each generation is bred from the best drivers so far. Speed trains up to 4× faster, your progress is saved in this browser, and Reset starts again from random cars.
AI Learns to Drive is a self-driving car simulation that runs entirely in the browser. Three hundred cars start on a three-lane road at the same time, each one steered by its own small neural network, and they have to work their way through slower traffic without hitting anything. Nobody tells them how to drive. The cars that do well pass their brains on to the next generation, and over time the population learns to overtake.
Everything is written in plain JavaScript and drawn on an HTML canvas. There are no libraries and no build step: the neural network, the physics, the collision detection and the visualizer are all written by hand.
How a car sees and decides
Each car has five ray sensors fanned out across the 90 degrees in front of it. Every frame, each ray reports how close the nearest obstacle is, whether that is the edge of the road or another car. Those five readings, plus the car’s own speed, are the inputs to a feed-forward network with one hidden layer of six neurons and four outputs: accelerate, steer left, steer right and reverse. The speed input matters: without it, a car can’t tell whether it needs to brake.
A panel beside the road draws the best car’s network live. Each connection is coloured by its weight, and moving dashes show the signal flowing through it at that moment. The outputs are labelled forward, left, right and reverse, and each one lights up while the car is pressing that control. Under the network, a small drawing of the car joins each sensor ray and a speed gauge to its input. Hovering over one picks out that ray on the road and the connections it feeds, and a caption says what it is reading, such as another car 60 pixels away, 45° to the left.
How the cars learn
There is no backpropagation here. Learning works by selection and mutation. In every generation, each brain drives three tracks: the main traffic layout and two random ones, with the same number of cars in each row but in different lanes. Because two of the three layouts change every generation, learning the main track by heart is not enough to rank well. Its results on the three tracks are added up, and the brains are ranked by how many tracks they finished, then by their total score.
The ten best become the parents of the next generation. Two brains that ended every track in exactly the same place count as the same driver, so the parents are all different drivers, and there can be fewer than ten. The parents carry over unchanged, so the best behaviour found so far is never lost. Every other car starts as a copy of a parent, with better parents getting more copies, and about one in ten of its weights and biases is nudged by a random amount. The Mutation slider sets how big the nudges are on average. Each generation tries a spread from tiny nudges up to twice that size, so it fine-tunes what already works and explores new behaviour at the same time.
If 20 generations go by without the best car on the main track getting further ahead, training counts as stuck and starts over with new random cars.
Scoring the right behaviour
The key design problem is deciding what “best” means. If distance alone is rewarded, a car can sit safely behind traffic forever, because that never crashes. So the score measures progress relative to traffic instead of distance on the road: a car only gains points by pulling ahead of the pack.
A few more rules keep training honest. A car whose score stops improving for a few seconds is treated as stalled and removed, which gets rid of tailgaters. Once a car has passed every vehicle, a finish line appears ahead of it, and the car finishes if it crosses the line while still in front of all the traffic. On each track, the camera follows the car in the lead: finishers beat non-finishers, and faster finishers beat slower ones.
Testing the scoring rule
To check that this rule really trains faster, I ran the real simulation code headless in Node, with seeded randomness and nothing drawn. I trained 8 sessions of 300 cars under each of three rules: progress relative to traffic, which is the rule the game uses; distance alone; and distance with a wall that moves up the road and removes any car that falls behind it, the rule from an earlier version of this project. For each seed, all three rules started from the same random cars. Every track was stopped after 60 seconds, because under distance alone a car that follows traffic never crashes or stalls.
Progress relative to traffic needed a median of 7 generations before one brain finished all three tracks. The wall needed 17, and distance alone needed 57.5, about eight times as many. Distance alone also got stuck and started over far more often: 22 times across its 8 sessions, against once for the game’s rule. When the 60 seconds ran out, a median of 212 of the 300 cars on each track were still sitting behind traffic.
Then I drove the 8 trained brains through 100 traffic layouts that no training run had used. Together they finished 335 of the 800 drives (42%), crashed in 388 and stalled in 77, and single brains finished between 16% and 68% of the layouts. What a brain learns carries over to new traffic, but only in part.
A hands-off training loop
Training runs by itself. A generation drives its three tracks one after another, and when every car on a track has crashed, stalled or finished, the next track or the next generation starts automatically. After each generation the parent brains are saved to the browser’s local storage. A stats bar shows the generation number, which track is running, how many cars are still alive, how many vehicles the leader has passed, and the elapsed time.
The simulation moves forward in fixed steps of 1/60 of a second, whatever the refresh rate of the screen. The Speed switch runs it at 1×, 2× or 4× by doing more steps per frame, so finish times stay the same at any speed.
When one brain finishes all three tracks in the same generation, training stops and that brain is kept. From then on, loading the page replays its run on the main track, until you press Reset and start again from random cars.
What I learned
- You get exactly what you reward. When the score only measured distance, most cars learned to follow traffic instead of passing it, and training took about eight times as many generations.
- Learning does not need complicated maths. Copying the best drivers and making small random changes is enough, as long as you repeat it many times.
- How big the random changes are matters. Big changes find new ideas quickly, and small changes polish a brain that already works.
- Being able to see the network makes problems much easier to understand. When a car makes a mistake, you can watch which sensor it reacted to.