1. Home
  2. AI & Machine Learning
  3. Genetic Algorithm

Genetic Algorithm

Evolve a solution like nature does: keep the fittest, mix their genes, add random mutations and repeat until the target appears.

Interactive 3DIntermediate12 min readAI/MLUpdated

Drag to rotate · Right-drag to pan · Click, then scroll to zoom · Space play · Left arrowRight arrow step

What's happening

A genetic algorithm evolves answers the way nature does: keep the fittest, mix them, add random mutations, repeat. Choose a target word and press Evolve.

Pseudocode

  1. population ← POP random strings
  2. repeat each generation:
  3. fitness(s) ← number of letters equal to the target
  4. sort by fitness; keep the best one (elitism)
  5. while the new population is not full:
  6. parents ← two winners of random 3-way tournaments
  7. child ← mix letters from both parents (crossover)
  8. each letter mutates to a random one with probability 0.2
  9. until a string equals the target
Read this model as text · 45 steps

One run of the model above, written out step by step. Useful with a screen reader, on a slow connection, or for quick revision. The values may differ from the run on your screen.

  1. A genetic algorithm evolves answers the way nature does: keep the fittest, mix them, add random mutations, repeat. Choose a target word and press Evolve.
  2. Generation 0: 16 random strings. Fitness = how many letters already equal the target HELLO. The best has fitness 2.
  3. Generation 1: selection, crossover and mutation produced a new population. Best fitness 2 / 5 (VNLQO).
  4. Generation 2: selection, crossover and mutation produced a new population. Best fitness 2 / 5 (VNLQO).
  5. Generation 3: selection, crossover and mutation produced a new population. Best fitness 2 / 5 (VNLQO).
  6. Generation 4: selection, crossover and mutation produced a new population. Best fitness 2 / 5 (VNLQO).
  7. Generation 5: selection, crossover and mutation produced a new population. Best fitness 3 / 5 (PELQO).
  8. Generation 6: selection, crossover and mutation produced a new population. Best fitness 3 / 5 (PELQO).
  9. Generation 7: selection, crossover and mutation produced a new population. Best fitness 3 / 5 (PELQO).
  10. Generation 8: selection, crossover and mutation produced a new population. Best fitness 3 / 5 (PELQO).
  11. Generation 9: selection, crossover and mutation produced a new population. Best fitness 3 / 5 (PELQO).
  12. Generation 10: selection, crossover and mutation produced a new population. Best fitness 4 / 5 (HELZO).
  13. Generation 11: selection, crossover and mutation produced a new population. Best fitness 4 / 5 (HELZO).
  14. Generation 12: selection, crossover and mutation produced a new population. Best fitness 4 / 5 (HELZO).
  15. Generation 13: selection, crossover and mutation produced a new population. Best fitness 4 / 5 (HELZO).
  16. Generation 14: selection, crossover and mutation produced a new population. Best fitness 4 / 5 (HELZO).
  17. Generation 15: selection, crossover and mutation produced a new population. Best fitness 4 / 5 (HELZO).
  18. Generation 16: selection, crossover and mutation produced a new population. Best fitness 4 / 5 (HELZO).
  19. Generation 17: selection, crossover and mutation produced a new population. Best fitness 4 / 5 (HELZO).
  20. Generation 18: selection, crossover and mutation produced a new population. Best fitness 4 / 5 (HELZO).
  21. Generation 19: selection, crossover and mutation produced a new population. Best fitness 4 / 5 (HELZO).
  22. Generation 20: selection, crossover and mutation produced a new population. Best fitness 4 / 5 (HELZO).
  23. Generation 21: selection, crossover and mutation produced a new population. Best fitness 4 / 5 (HELZO).
  24. Generation 22: selection, crossover and mutation produced a new population. Best fitness 4 / 5 (HELZO).
  25. Generation 23: selection, crossover and mutation produced a new population. Best fitness 4 / 5 (HELZO).
  26. Generation 24: selection, crossover and mutation produced a new population. Best fitness 4 / 5 (HELZO).
  27. Generation 25: selection, crossover and mutation produced a new population. Best fitness 4 / 5 (HELZO).
  28. Generation 26: selection, crossover and mutation produced a new population. Best fitness 4 / 5 (HELZO).
  29. Generation 27: selection, crossover and mutation produced a new population. Best fitness 4 / 5 (HELZO).
  30. Generation 28: selection, crossover and mutation produced a new population. Best fitness 4 / 5 (HELZO).
  31. Generation 29: selection, crossover and mutation produced a new population. Best fitness 4 / 5 (HELZO).
  32. Generation 30: selection, crossover and mutation produced a new population. Best fitness 4 / 5 (HELZO).
  33. Generation 31: selection, crossover and mutation produced a new population. Best fitness 4 / 5 (HELZO).
  34. Generation 32: selection, crossover and mutation produced a new population. Best fitness 4 / 5 (HELZO).
  35. Generation 33: selection, crossover and mutation produced a new population. Best fitness 4 / 5 (HELZO).
  36. Generation 34: selection, crossover and mutation produced a new population. Best fitness 4 / 5 (HELZO).
  37. Generation 35: selection, crossover and mutation produced a new population. Best fitness 4 / 5 (HELZO).
  38. Generation 36: selection, crossover and mutation produced a new population. Best fitness 4 / 5 (HELZO).
  39. Generation 37: selection, crossover and mutation produced a new population. Best fitness 4 / 5 (HELZO).
  40. Generation 38: selection, crossover and mutation produced a new population. Best fitness 4 / 5 (HELZO).
  41. Generation 39: selection, crossover and mutation produced a new population. Best fitness 4 / 5 (HELZO).
  42. Generation 40: selection, crossover and mutation produced a new population. Best fitness 4 / 5 (HELZO).
  43. Generation 41: selection, crossover and mutation produced a new population. Best fitness 4 / 5 (HELZO).
  44. Generation 42: selection, crossover and mutation produced a new population. Best fitness 5 / 5 (HELLO). Target reached!
  45. Evolved HELLO in 42 generations, checking only about 672 strings. Random guessing would need about 26^5 = 11,881,376 tries.

Try this in the 3D model

  • Press Evolve on HELLO. How many generations does it take, and how fast does the best fitness rise at first?
  • Press New seed and evolve again. Is the number of generations the same? Why not?
  • Try a 3-letter target and then a 6-letter one. How does the effort grow with the length?
  • Watch the bottom rows: how do the weakest strings change from generation to generation?

Evolution as an algorithm

Some problems have no formula and too many possibilities to try them all, for example designing a timetable or the shape of an antenna. A genetic algorithm (GA) searches by imitating natural selection.

The loop

  1. Population: start with many random candidate solutions.
  2. Fitness: score each candidate.
  3. Selection: pick parents, favouring higher scores. Here each parent is the winner of a random 3-way tournament.
  4. Crossover: build a child by mixing the letters of two parents.
  5. Mutation: with probability 0.2 each letter is replaced by a random one.
  6. Elitism: the best individual is copied unchanged into the next generation.
  7. Repeat until a good enough solution appears.
population ← random strings
repeat:
    sort by fitness
    new ← [best]
    while len(new) < size:
        a, b ← tournament(), tournament()
        child ← crossover(a, b)
        new.append(mutate(child))
    population ← new
until best == target

Why it works

Selection gives good letters a better chance to spread, crossover combines them in new ways, and mutation keeps supplying variety. Each generation is slightly better than the last, so a 5-letter word that has 26⁵ = 11,881,376 possibilities is typically found after only a few hundred evaluations.

Strengths and weaknesses

Strengths Weaknesses
Needs only a fitness score, not a gradient No guarantee of the global best
Works on discrete and messy problems Many parameters to tune (population, mutation rate)
Easy to parallelise Fitness evaluation can be expensive

Compare with gradient descent, which follows a smooth slope, and with N-Queens backtracking, which tries possibilities systematically.

Code

import random, string

def evolve(target, pop_size=16, mutation=0.2, max_gen=80):
    L, A = len(target), string.ascii_uppercase
    fit = lambda s: sum(a == b for a, b in zip(s, target))
    pop = [''.join(random.choice(A) for _ in range(L)) for _ in range(pop_size)]
    for gen in range(max_gen + 1):
        pop.sort(key=fit, reverse=True)
        if pop[0] == target:
            return gen
        tour = lambda: max(random.sample(pop, 3), key=fit)
        new = [pop[0]]
        while len(new) < pop_size:
            a, b = tour(), tour()
            child = ''.join(x if random.random() < 0.5 else y for x, y in zip(a, b))
            child = ''.join(random.choice(A) if random.random() < mutation else c for c in child)
            new.append(child)
        pop = new
    return None

Common mistakes

  • A mutation rate that is too low makes the population converge to a poor answer. One that is too high turns the search into random guessing.
  • Forgetting elitism, so the best solution can be lost.
  • A fitness function that does not reward partial progress, which gives selection nothing to work with.
  • Expecting the same result every run. The algorithm is random, so use a seed to repeat an experiment.

Complexity at a glance

Case / operationTimeWhy
One generationO(P · L)P individuals of length L: evaluate, select, cross over, mutate.
Generations neededproblem dependentNo guarantee of finding the optimum, but usually far fewer evaluations than brute force.
Extra spaceO(P · L)

Quick check

Test yourself — pick an answer to see if you got it.

1. What does the fitness function do?

2. What is the purpose of crossover?

3. Why is mutation necessary?

4. What does elitism (keeping the best individual unchanged) prevent?

Saved in this browser.
Spotted a mistake or a bug in the 3D model?

Report a mistake

in Genetic Algorithm. Thank you — every report makes the lesson better for the next reader.

We'll also include a link to the step of the 3D model you're on and your browser type, so we can reproduce it.