Playground
Genetic algorithm: cars learn to drive

Evolution instead of training

Genetic algorithm A population of random solutions is tested. The best ones are picked more often as parents. A child mixes the genes of two parents and some genes change a little (mutation). The best solutions of a generation can also be copied unchanged (elite). After some generations the solutions are much better. Wikipedia

Neural net driver Each car has a small neural net: 5 distance sensors and the speed go in, steering and throttle come out. The genome is the list of its 56 weights. No weight is trained by gradient. The genetic algorithm only changes the weights from generation to generation. This idea is called neuroevolution. Wikipedia

Original work

How it works

Every generation, all cars drive the track at the same time.

  • Sensors measure the distance to the walls. The net turns this into steering and throttle. A car that touches a wall, or makes no progress for 3 seconds, is out.
  • Fitness is the progress along the track in laps. A car that finishes a lap gets more fitness the faster it is.
  • Parents come from a tournament: 3 random cars compete and the fittest wins.
  • A child takes each gene from one of two parents, then mutation changes some genes. The elite cars are copied unchanged.
  • The time step is fixed and a seeded random generator makes every choice, so the same link gives the same evolution. Mutation and elite changes count from the next generation.

Source code:ga-cars-evolution.tsga-cars-genetics.tsga-cars-net.tsga-cars-race.tsga-cars-track.tsga-cars.model.ts

Note Simplifications in this demo:

  • The net has a fixed shape. Only the weights evolve. Methods like NEAT also evolve the shape.
  • Simple movement: no grip, no sliding, the car is a circle.
  • Hard tracks need many generations, and some seeds never finish a lap. A car trained on the easy track often fails on the others.
  • Fitness: 1 means one lap. More than 1 means a faster lap.
Seed
Population (restarts)
Mutation rate
Mutation strength
Elite cars
Speed (x real time)
Frames/s: 0Generation: 0Cars driving: 0 / 0Best fitness (last generation): -Mean fitness (last generation): -Fastest lap: -

Best Mean One lap