Overview
A genetic algorithm keeps many candidate solutions at once. Each is a list of numbers called a genome. Every generation, the candidates are scored. Better ones are more likely to be chosen as parents. Two parents are combined to make a child that carries parts of both, and a little random noise is added so that new values can appear. Over generations, pieces of good solutions spread through the population and combine. No gradient is needed, only a score for each candidate. When the genome holds the weights of a small neural network, this is called neuroevolution.
A short history
John Holland developed genetic algorithms at the University of Michigan in the 1960s and set them out in his 1975 book Adaptation in Natural and Artificial Systems. David Goldberg's 1989 textbook made them widely known. They answered the need for a search method on problems with no gradient and awkward, discrete structure. Neuroevolution applied them to neural networks, for example in NEAT by Kenneth Stanley and Risto Miikkulainen in 2002.
How it works
- Build the first population: the starting genome x0 plus copies of it with random noise of size init_sigma.
- ask returns the population. Evaluate every genome and pass the scores to tell. Lower is better.
- Copy the elite_count best genomes unchanged into the next generation. This is elitism, and it guarantees the best score never gets worse.
- Choose each parent by a tournament: draw tournament_size genomes at random and take the best of them.
- With probability crossover_rate, combine two parents into a child by the chosen crossover. Otherwise the child is a copy of the first parent.
- Mutate the child: each gene, with probability mutation_rate, gets normal noise of size sigma added.
- The elites and the children form the new population. sigma is multiplied by sigma_decay, and the loop repeats.
Watch out for
- Strong selection, such as a large tournament with many elites, fills the population with near copies of one genome. Crossover then has nothing to combine and the search stalls at a local optimum.
- A mutation size that is too large destroys good genomes faster than selection can keep them. One that is too small cannot escape a local optimum.
- Crossover helps only when parts of a genome are useful on their own. Mixing the weights of two different neural networks often yields a child worse than both.
- It needs population size times generations evaluations. For smooth problems with a gradient that is far more work than gradient descent.
- This is a basic real-valued version. It has no self-adapting mutation size and no mechanism to keep the population diverse.
Use cases
When to use it
When the objective has no usable gradient, is rugged or discontinuous, or when solutions are built from parts that can be recombined. It suits small neural networks, design problems and game-playing policies.
In industry
- Aerospace
- NASA used an evolutionary algorithm to design the antenna flown on its ST5 spacecraft in 2006, a shape no engineer would have drawn by hand.
- Scheduling and logistics
- Planners use genetic algorithms for timetables, job shop schedules and vehicle routes, where solutions are orderings or assignments.
- Machine learning
- Neuroevolution searches network weights or architectures, and has been shown to train game-playing agents without gradients.
Choosing it: what must hold
- A way to encode a candidate solution so that crossover and mutation produce valid candidates.
- A fitness function that can score any candidate, with or without gradients.
- A budget for many evaluations: population size times generations.
- Tolerance for a good solution, not a proven best one.
When to choose something else
| If | Use instead |
|---|---|
| The problem is continuous and differentiable | A gradient-based optimizer such as SGD or Adam |
| The problem is continuous with no gradient and modest dimension | CMA-ES |
| The parameters are a large neural network scored by episode reward | OpenAI-style evolution strategies, or a policy gradient method |
| The problem has a known exact method, such as linear or integer programming | That exact solver |
Math foundations
Tournament selection
The chance that the genome ranked (1 is best) wins a tournament of random draws from , with no ties. It wins when every entrant is ranked or worse and not all are strictly worse. A larger favours the top ranks more.
Blend crossover
Each gene of the child is a random point between the two parents' genes. Uniform crossover instead copies each gene whole from one parent or the other with equal chance, and one-point crossover takes the first genes from one parent and the rest from the other.
Gaussian mutation
Each gene is changed with probability by adding normal noise of standard deviation . On average genes of a child are mutated.
Shrinking the mutation size
With a decay below 1 the mutations start large, to explore, and become small, to fine-tune. With the size stays fixed.
Symbols
- population_size
- tournament_size
- the rank of a genome by fitness, 1 for the best
- gene j of the two parents and of the child
- a random mixing number between 0 and 1
- mutation_rate, the chance that one gene is mutated
- the current mutation size and its starting value (mutation_sigma)
- sigma_decay
- the number of genes in a genome (dim)
- the generation number
Worked by hand
Use the defaults , and with genomes of genes. Find the chance that the best genome wins a given tournament, and the chance that a child passes through mutation unchanged.
A tournament of 3 makes the best genome about three times as likely to be a parent as under pure chance. About two genes change per child, and roughly one child in eight is not mutated at all.
Visual example
Loading the example.
Try this
- Raise the mutation size: more exploring, less settling.
- Step slowly and watch the best half become the parents.
Code sample
import numpy as np
from impl import GeneticAlgorithm
from config import GeneticConfig
target = np.array([1.0, -2.0, 3.0])
ga = GeneticAlgorithm(x0=np.zeros(3), config=GeneticConfig(mutation_sigma=0.3, sigma_decay=0.97, seed=0))
best_x, best_f = ga.minimize(lambda x: float(np.sum((x - target) ** 2)), generations=200)
print(best_x, best_f) # close to [1, -2, 3], fitness near 0Read the implementation (94 lines)
"""Genetic algorithm on real-valued genomes: tournament selection, crossover, Gaussian mutation, elitism.
NumPy only. A genome is a flat float vector, so it can hold the parameters of any function, including the
weights of a small neural network (neuroevolution: flatten the weights, let the fitness function run the
network). Fitness is minimised. Use the ask / tell loop or the `minimize` helper.
"""
from __future__ import annotations
import math
import numpy as np
try:
from .config import GeneticConfig
except ImportError: # run from the template's own folder
from config import GeneticConfig
class GeneticAlgorithm:
"""Evolves a population of genomes.
x0: starting genome, shape (dim,). The first population is x0 itself plus copies perturbed with
`init_sigma`. State: `population` (population_size, dim), `sigma` (current mutation strength),
`generation`, `best_x` (dim,) and `best_f`.
"""
def __init__(self, x0, config: GeneticConfig | None = None) -> None:
self.config = cfg = config or GeneticConfig()
x0 = np.array(x0, dtype=float).reshape(-1)
self.dim = x0.shape[0]
self.rng = np.random.default_rng(cfg.seed)
self.population = x0 + cfg.init_sigma * self.rng.standard_normal((cfg.population_size, self.dim))
self.population[0] = x0
self.sigma = float(cfg.mutation_sigma)
self.generation = 0
self.best_x = x0.copy()
self.best_f = math.inf
def ask(self) -> np.ndarray:
"""The current population to evaluate, shape (population_size, dim)."""
return self.population.copy()
def _select(self, fitness: np.ndarray, count: int) -> np.ndarray:
"""Tournament selection. Returns `count` parent indices; each is the fittest of a random draw."""
entrants = self.rng.integers(0, len(fitness), size=(count, self.config.tournament_size))
return entrants[np.arange(count), np.argmin(fitness[entrants], axis=1)]
def _crossover(self, a: np.ndarray, b: np.ndarray) -> np.ndarray:
"""Children of the parent pairs (a[i], b[i]). a, b: (count, dim). Returns (count, dim)."""
cfg, count = self.config, a.shape[0]
if cfg.crossover == "uniform":
children = np.where(self.rng.random(a.shape) < 0.5, a, b)
elif cfg.crossover == "blend":
mix = self.rng.random(a.shape)
children = mix * a + (1.0 - mix) * b
else: # one_point
cut = self.rng.integers(1, max(self.dim, 2), size=(count, 1))
children = np.where(np.arange(self.dim)[None, :] < cut, a, b)
crossed = self.rng.random((count, 1)) < cfg.crossover_rate
return np.where(crossed, children, a)
def tell(self, fitnesses) -> None:
"""Build the next generation from the fitness (lower is better) of the current population.
fitnesses: shape (population_size,), in the order of `ask()`.
"""
cfg = self.config
f = np.asarray(fitnesses, dtype=float).reshape(-1)
if f.shape[0] != cfg.population_size:
raise ValueError(f"expected {cfg.population_size} fitness values, got {f.shape[0]}")
order = np.argsort(f, kind="stable")
if f[order[0]] < self.best_f:
self.best_f, self.best_x = float(f[order[0]]), self.population[order[0]].copy()
elites = self.population[order[: cfg.elite_count]]
n_children = cfg.population_size - cfg.elite_count
parents_a = self.population[self._select(f, n_children)]
parents_b = self.population[self._select(f, n_children)]
children = self._crossover(parents_a, parents_b)
mutate = self.rng.random(children.shape) < cfg.mutation_rate
children = children + mutate * self.sigma * self.rng.standard_normal(children.shape)
self.population = np.vstack([elites, children])
self.sigma *= cfg.sigma_decay
self.generation += 1
def minimize(self, fn, generations: int = 100, target: float | None = None) -> tuple[np.ndarray, float]:
"""Minimise fn(genome) -> float, genome of shape (dim,). Returns (best_x, best_f).
Runs `generations` generations, or stops early once the best fitness is at or below `target`.
"""
for _ in range(generations):
self.tell([fn(x) for x in self.population])
if target is not None and self.best_f <= target:
break
return self.best_x.copy(), self.best_f- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 7, run with
python3 -m unittest -v
Practice
Minimise the Rastrigin function in 5 dimensions, , with GeneticAlgorithm.minimize from the start . Using GeneticConfig, compare tournament_size 2 and 10, and the three crossover choices. For each run, track best_f and the spread of the population per generation through ask and tell, and note which settings lose diversity first.
Check on learning
- What happens to the population if tournament_size is set equal to population_size and elite_count is high? Why does the search then stop improving?
A way to think about it
Work out which genome wins nearly every tournament. Then ask what crossover of a genome with a copy of itself produces.
- Why does crossover often hurt when the genomes are neural network weights, even when both parents perform well?
A way to think about it
Two networks can compute the same function with their hidden units in a different order. Consider what mixing unit 3 of one with unit 3 of the other means.
- With elitism the best score can never get worse from one generation to the next. Is that always a good thing when the scores are noisy?
A way to think about it
Think of a genome that scored well once by luck. Elitism keeps it for ever unless it is evaluated again.
- Compare a genetic algorithm with gradient descent on a smooth bowl in 1000 dimensions. Roughly how does the cost of one useful step compare?
A way to think about it
A gradient gives the best direction in one evaluation plus a backward pass. A random mutation in 1000 dimensions is almost always nearly perpendicular to it.