TExcelTAD
Home › Optimization › Genetic Algorithms

Genetic Algorithms

Genetic algorithms (GAs) and other evolutionary methods keep a whole population of candidate solutions and improve it with selection, recombination and mutation, imitating natural evolution. They need only function values, handle discrete, continuous and mixed variables, and parallelize naturally. They are rarely the most efficient method for a well-structured problem, but they are a flexible tool for messy ones.

The loop

  1. Initialize a population of NN random candidates.
  2. Evaluate each one's fitness (objective value).
  3. Select parents, favouring fitter candidates (tournament selection: pick a few at random, keep the best).
  4. Crossover: combine two parents into children (for bit strings, cut both at a random point and swap tails).
  5. Mutate: make small random changes so new material keeps appearing.
  6. Keep the best few unchanged (elitism) and repeat.

A 0/1 knapsack with a GA

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
n = 40
values = rng.integers(10, 100, size=n); weights = rng.integers(5, 50, size=n); cap = weights.sum() // 3
def fitness(pop):
    v, w = pop @ values, pop @ weights
    return np.where(w <= cap, v, v - 10 * (w - cap))          # penalize overweight solutions

pop = (rng.uniform(size=(80, n)) < 0.2).astype(int)
for gen in range(200):
    fit = fitness(pop)
    elite = pop[np.argsort(fit)[-4:]]
    a, b = rng.integers(80, size=(2, 76)), rng.integers(80, size=(2, 76))
    parents1 = pop[np.where(fit[a[0]] > fit[a[1]], a[0], a[1])]      # tournament selection
    parents2 = pop[np.where(fit[b[0]] > fit[b[1]], b[0], b[1])]
    cut = rng.integers(1, n, size=76)[:, None]
    children = np.where(np.arange(n) < cut, parents1, parents2)      # one-point crossover
    children ^= (rng.uniform(size=children.shape) < 1 / n).astype(int)   # bit-flip mutation
    pop = np.vstack([elite, children])
best = pop[np.argmax(fitness(pop))]
print("GA best value:", int(best @ values), " weight:", int(best @ weights), "/", int(cap))

from scipy.optimize import milp, LinearConstraint, Bounds
exact = milp(-values.astype(float), constraints=LinearConstraint(weights, ub=cap), integrality=np.ones(n), bounds=Bounds(0, 1))
print("exact optimum (MILP):", int(round(-exact.fun)))
GA best value: 1265  weight: 386 / 387
exact optimum (MILP): 1265

Here the GA reaches the optimal value 1265 with no problem-specific machinery (on other seeds it may stop a little short). Only the MILP solver proves that 1265 is optimal, which a GA never can.

Continuous problems: differential evolution

For real-valued variables, differential evolution (DE) builds a mutant from three population members, v=a+F(b−c)\mathbf{v} = \mathbf{a} + F(\mathbf{b} - \mathbf{c}), mixes it with the current member coordinate-wise, and keeps it if it is better. The difference vectors automatically adapt to the scale of the population, so DE needs little tuning.

python · try it yourself
import numpy as np
from scipy.optimize import differential_evolution

f = lambda x: 10 * len(x) + np.sum(x**2 - 10 * np.cos(2 * np.pi * x))       # Rastrigin in 5D
r = differential_evolution(f, bounds=[(-5.12, 5.12)] * 5, seed=1, tol=1e-10, maxiter=3000)
print("DE:", np.round(r.x, 4) + 0, " f =", round(r.fun, 6) + 0, " evaluations:", r.nfev)
DE: [0. 0. 0. 0. 0.]  f = 0.0  evaluations: 14106

Other population methods

Method Idea
CMA-ES sample from a Gaussian, adapt its mean and covariance toward good samples; state of the art for hard continuous black boxes
particle swarm particles move with velocity pulled toward their own and the swarm's best points
NSGA-II genetic algorithm for multi-objective problems, returning a Pareto front
genetic programming evolve programs or formulas (symbolic regression)

When (not) to use them

Use evolutionary methods when the problem is a black box, multimodal, mixed discrete-continuous, or when you need a quick result with little modelling. Avoid them when gradients exist (use gradient methods), when the problem is an LP/QP/MILP (use a solver with guarantees), or when evaluations are extremely expensive (use Bayesian optimization).

In software

  • scipy.optimize.differential_evolution, pycma (CMA-ES), DEAP, pymoo (multi-objective), Nevergrad.
  • Evolution strategies are used in reinforcement learning (OpenAI's ES), neural architecture search, antenna and aerodynamic shape design.

Exercises

Exercise 1: One-point crossover

Parents 110010 and 001111, cut after position 2. What are the two children?

Answer

111111 and 000010.

Solution

Child 1 takes the first 2 bits of parent 1 (11) and the rest of parent 2 (1111); child 2 takes 00 from parent 2 and 0010 from parent 1.

Exercise 2: Mutation rate

With bit strings of length 40 and a per-bit mutation probability of 1/401/40, how many bits flip per child on average? What is the chance that none flips?

Answer

1 on average; about 36.3% chance of no flip.

Solution

The number of flips is binomial with mean 40⋅140=140 \cdot \frac{1}{40} = 1; P(0)=(39/40)40≈0.363≈e−1P(0) = (39/40)^{40} \approx 0.363 \approx e^{-1}.

Exercise 3: Without elitism (code)

Rerun the knapsack GA without the 4 elite members (all 80 children). Does the best value get worse?

Answer

Yes: the final population's best is 1186, below the best solution it had seen (1256), and neither reaches 1265. Without elitism, good solutions are lost to crossover and mutation.

Solution
python · try it yourself
import numpy as np
rng = np.random.default_rng(0)
n = 40
values = rng.integers(10, 100, size=n); weights = rng.integers(5, 50, size=n); cap = weights.sum() // 3
fitness = lambda pop: np.where(pop @ weights <= cap, pop @ values, pop @ values - 10 * (pop @ weights - cap))
pop = (rng.uniform(size=(80, n)) < 0.2).astype(int); best_ever = 0
for gen in range(200):
    fit = fitness(pop)
    a, b = rng.integers(80, size=(2, 80)), rng.integers(80, size=(2, 80))
    p1 = pop[np.where(fit[a[0]] > fit[a[1]], a[0], a[1])]; p2 = pop[np.where(fit[b[0]] > fit[b[1]], b[0], b[1])]
    cut = rng.integers(1, n, size=80)[:, None]
    pop = np.where(np.arange(n) < cut, p1, p2) ^ (rng.uniform(size=(80, n)) < 1 / n).astype(int)
    best_ever = max(best_ever, int(fitness(pop).max()))
print("final population best:", int(fitness(pop).max()), " best ever seen:", best_ever)
final population best: 1186  best ever seen: 1256

Test yourself

Tournament selection…

  1. picks a few random candidates and keeps the fittest
  2. always picks the overall best
  3. selects uniformly at random
  4. sorts the whole population each time

What does elitism do in a genetic algorithm?

  1. Copies the best candidates unchanged into the next generation
  2. Removes the best candidates
  3. Doubles the mutation rate
  4. Stops the algorithm early

Which advantage does a MILP solver have over a GA for a knapsack problem?

  1. It proves optimality
  2. It needs no model
  3. It only uses function values
  4. It is always slower