Can a computer write a program by itself, just by being told what a good answer looks like? Genetic programming (GP) does exactly that, by borrowing a trick from nature: evolution. This tutorial assumes no background in evolutionary computation. Every idea comes with a demo you can play with in your browser, and every demo has a Show Python code button with a complete, commented program you can copy and run yourself.

~30 minreading and playing time
6interactive demos
Pythoncode for every demo, ready to copy and run
Beginnerhigh-school maths is enough

1. Evolution in a Nutshell

Evolutionary computation solves problems the way nature produces well-adapted organisms. You start with a population of random candidate solutions, and repeat four steps for many generations:

1EvaluateScore each candidate with a fitness function.
2SelectFitter candidates are more likely to become parents.
3VaryCrossover mixes two parents; mutation makes small random changes.
4ReplaceThe children form the next generation. Repeat!

No single step is clever. The power comes from selection accumulating small improvements over many generations. Try it: the demo below evolves random letters into a target phrase. Guessing the phrase at random would take longer than the age of the universe; evolution usually needs only a few dozen generations.

Note: Demo 1 is a genetic algorithm (GA), not genetic programming. Each candidate is a fixed-length string of letters, not a program. We use it because the evolutionary loop is easiest to see on strings. Genetic programming, from Section 2 onwards, runs the same loop on programs (trees) of varying size and shape.
Demo 1 · Evolve a phrase with a genetic algorithm (GA)

Generation · correct letters

Other individuals in the population:

    Chance of guessing the phrase at random:

    Try this:
    • Set the mutation rate to 0. Evolution gets stuck once the population loses the letters it needs. Mutation keeps diversity alive.
    • Set it to 20%. Good letters get destroyed as fast as they are found. Too much randomness is as bad as too little.
    • Set the tournament size to 1 (random parents, no selection). Progress stalls: without selection there is no evolution.

    2. From Strings to Programs: Trees

    In Demo 1 each candidate was a fixed-length string: that was a genetic algorithm. Genetic programming evolves computer programs instead, and programs are naturally represented as trees:

    • Functions sit at the inner nodes: +, −, ×, ÷ here, but they could be if, max, sin or any operation useful for the problem.
    • Terminals sit at the leaves: inputs such as x, and constants such as 1, 2, 0.5.
    • To run the program, evaluate from the leaves up: each function node combines the values of its children.

    Together, the function set and terminal set are GP's building blocks: they define what programs can possibly be evolved. Division is protected (dividing by zero returns 1), so that every random program can run without crashing.

    Demo 2 · Sample a random program, step by step
    Function set F (inner nodes, each takes 2 inputs)
    +−×÷
    ÷ is protected: dividing by (almost) zero returns 1.
    Terminal set T (leaves, take no inputs)
    x1230.5
    The input x is chosen 60% of the time, a constant 40%.
    Step of

    Program:  →  output (size nodes, depth )

    The orange node was just decided; the dashed ? slot is the next one to fill. The symbol just picked is highlighted in the sets above.

    Try this: Step through a Full tree (every slot above the maximum depth is a function, so every branch reaches the maximum depth) and then a Grow tree (each slot draws a random number, so branches may stop early). GP usually starts with a mix of both, called ramped half-and-half, so the first generation contains programs of many shapes and sizes.

    3. Crossover and Mutation on Trees

    The variation operators from Demo 1 have tree versions:

    • Subtree crossover picks a random node in each of two parents and swaps the subtrees below them. Useful sub-expressions found by one program can be combined with those of another.
    • Subtree mutation picks a random node and replaces its subtree with a new random one, bringing new genetic material into the population.
    Demo 3 · Crossover and mutation, step by step
    Step of

      4. Fitness: How Good Is a Program?

      Evolution needs a way to compare programs. A common first task for GP is symbolic regression: given some data points, find a formula that fits them. Here the hidden formula is x² + x, and we only see 21 sample points.

      The fitness of a program is how far its outputs are from the data. We use the root mean squared error (RMSE): run the program on every input, square each error, average them, and take the square root. Lower is better; 0 means a perfect fit.

      Demo 4 · Score some candidate programs
      Pick a candidate:

      RMSE =

      Dots are the target data. The line is the candidate's output. The red bars are its errors at each data point: the fitness summarises them in one number.

      The fitness cases. Each row is one fitness case: an input x and the output y the program should produce. Run the program on the input, compare with the target, and square the error. Hover over a row to see its error on the chart.

      #input xtarget y = x² + xprogram outputerror (output − y)squared error

      Selection then favours programs with lower error. GP never needs to know how to solve the problem, only how to measure a solution. This is what makes it so general.

      5. Putting It Together: Run Genetic Programming

      Now everything comes together. The demo below runs a real GP algorithm in your browser:

      1. Create a random population with ramped half-and-half.
      2. Measure every program's error on the 21 data points.
      3. Choose parents by tournament selection: pick a few programs at random and keep the best.
      4. Make each child with one operator: crossover (80% of children), mutation (the mutation rate), or copying a parent unchanged (the rest). The best program always survives (elitism).
      5. Repeat until the formula is found or the generations run out.
      Demo 5 · Evolve a formula (symbolic regression)

      Generation · best error · best program size · average size

      Best program:
      How well the best program fits the data
      Best error over generations
      Average program size over generations
      Show the best program as a tree
      Try this:
      • Press Run on Koza's quartic x⁴ + x³ + x² + x, the classic benchmark from John Koza's 1992 book. It is usually found within 5–15 generations. Press New random population and run again: every run takes a different path, because GP is stochastic.
      • Try x² + x: it is so simple that a perfect program is sometimes already in the random first generation. Then try a population of 50 and see how much harder the search becomes.
      • Try sin(x). With only + − × ÷ GP cannot write sin exactly, but it finds a good approximation, much like a Taylor series.
      • Set the tournament size to 1 again: without selection pressure, the error barely improves.

      6. Bloat: When Programs Grow Too Big

      Watch the average program size chart in Demo 5 during a long run (try sin(x) with 200 generations). Programs often keep growing even when the error stops improving. This is called bloat.

      Bloat happens largely because of introns: pieces of code that have no effect, such as (x − x) or × 1. They protect useful code from destructive crossover, so they get selected for, and they accumulate.

      Bloat makes evolution slower and the results harder to read. Common remedies are depth limits (Demo 5 caps trees at depth 8), simplifying programs, and parsimony pressure, which adds a small penalty for size to the fitness.

      Experiment: run sin(x) for 200 generations twice, once with Penalise large programs off and once on. Compare the average-size charts and the readability of the best programs.

      Keeping programs small is also central to explainable AI: a short formula can be read and trusted by people. You can find out more on my Explainable AI research page.

      7. Genetic Programming in the Real World

      Symbolic regression is just the start. Because GP evolves programs, it can design decision rules for problems where people normally hand-craft heuristics. In my research, GP evolves rules that make real-time decisions in dynamic environments:

      Job shop scheduling

      Which waiting job should a machine process next? GP evolves priority rules such as PT + WINQ ÷ NOR, built from features like processing time (PT) and work in the next queue (WINQ).

      Vehicle and arc routing

      Which task should a vehicle serve next when demands are uncertain? GP evolves routing policies that react instantly.

      Traffic signal control

      When should a light change? Evolved policies won the GP track Best Paper Award at GECCO 2024.

      Cloud computing

      Where should tasks and containers run? GP learns scheduling heuristics for workflows in the cloud.

      The recipe is the same as in Demo 5. Replace the data points with a simulation of the factory, fleet or network, use features of the current situation as terminals, and measure fitness by how well the rule performs in simulation. Read more on my research page, Genetic Programming for Real-time Optimisation and Decision-Making.

      8. Check Your Understanding

      1. In a GP tree, where do the inputs (such as x) appear?

      2. What happens if you switch off mutation entirely?

      3. Two programs both fit the data perfectly: x × x + x and ((x × x) + (x − x)) + (x ÷ 1). Which would parsimony pressure prefer?

      4. What does GP need to be told in order to solve a problem?

      Where to Go Next