Sign in

Genetic

Genetic algorithm

A search method modelled on natural selection: it keeps a population of candidate solutions and breeds the better ones to form the next generation.

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

  1. Build the first population: the starting genome x0 plus copies of it with random noise of size init_sigma.
  2. ask returns the population. Evaluate every genome and pass the scores to tell. Lower is better.
  3. Copy the elite_count best genomes unchanged into the next generation. This is elitism, and it guarantees the best score never gets worse.
  4. Choose each parent by a tournament: draw tournament_size genomes at random and take the best of them.
  5. With probability crossover_rate, combine two parents into a child by the chosen crossover. Otherwise the child is a copy of the first parent.
  6. Mutate the child: each gene, with probability mutation_rate, gets normal noise of size sigma added.
  7. 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

IfUse instead
The problem is continuous and differentiableA gradient-based optimizer such as SGD or Adam
The problem is continuous with no gradient and modest dimensionCMA-ES
The parameters are a large neural network scored by episode rewardOpenAI-style evolution strategies, or a policy gradient method
The problem has a known exact method, such as linear or integer programmingThat exact solver

Math foundations

  1. Tournament selection

    P(rank r wins)=(N−r+1N)s−(N−rN)sP(\text{rank } r \text{ wins}) = \left(\frac{N - r + 1}{N}\right)^{s} - \left(\frac{N - r}{N}\right)^{s}

    The chance that the genome ranked rr (1 is best) wins a tournament of ss random draws from NN, with no ties. It wins when every entrant is ranked rr or worse and not all are strictly worse. A larger ss favours the top ranks more.

  2. Blend crossover

    cj=uj aj+(1−uj) bj,uj∼U(0,1)c_j = u_j\,a_j + (1 - u_j)\,b_j, \qquad u_j \sim U(0, 1)

    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.

  3. Gaussian mutation

    cj′=cj+zj σ εj,zj∼Bernoulli⁡(pm),εj∼N(0,1)c_j' = c_j + z_j\,\sigma\,\varepsilon_j, \qquad z_j \sim \operatorname{Bernoulli}(p_m), \quad \varepsilon_j \sim \mathcal{N}(0, 1)

    Each gene is changed with probability pmp_m by adding normal noise of standard deviation σ\sigma. On average pmdp_m d genes of a child are mutated.

  4. Shrinking the mutation size

    σt=σ0 γ t\sigma_t = \sigma_0\,\gamma^{\,t}

    With a decay γ\gamma below 1 the mutations start large, to explore, and become small, to fine-tune. With γ=1\gamma = 1 the size stays fixed.

Symbols

NN
population_size
ss
tournament_size
rr
the rank of a genome by fitness, 1 for the best
aj, bj, cja_j,\ b_j,\ c_j
gene j of the two parents and of the child
uju_j
a random mixing number between 0 and 1
pmp_m
mutation_rate, the chance that one gene is mutated
σ, σ0\sigma,\ \sigma_0
the current mutation size and its starting value (mutation_sigma)
γ\gamma
sigma_decay
dd
the number of genes in a genome (dim)
tt
the generation number

Worked by hand

Use the defaults N=50N = 50, s=3s = 3 and pm=0.1p_m = 0.1 with genomes of d=20d = 20 genes. Find the chance that the best genome wins a given tournament, and the chance that a child passes through mutation unchanged.

P(rank 1 wins)=1−(4950)3=1−0.9412=0.0588P(\text{rank } 1 \text{ wins}) = 1 - \left(\frac{49}{50}\right)^{3} = 1 - 0.9412 = 0.0588
with s=1:1−4950=0.02\text{with } s = 1: \quad 1 - \frac{49}{50} = 0.02
pm d=0.1×20=2 genes mutated on averagep_m\,d = 0.1 \times 20 = 2 \text{ genes mutated on average}
P(no gene mutated)=0.920≈0.122P(\text{no gene mutated}) = 0.9^{20} \approx 0.122

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 0
Read 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, f(x)=50+∑j(xj2−10cos⁡(2πxj))f(x) = 50 + \sum_j \big(x_j^2 - 10 \cos(2\pi x_j)\big), with GeneticAlgorithm.minimize from the start (3,3,3,3,3)(3, 3, 3, 3, 3). 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

  1. 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.

  2. 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.

  3. 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.

  4. 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.