Genetic Algorithms

Evolution is the most successful optimizer we know of. With no gradient, no plan and no understanding, it produced eyes, wings and brains, just by repeating three steps over and over: variation (offspring differ from their parents), selection (fitter individuals reproduce more) and inheritance (offspring resemble their parents). John Holland turned this into an algorithm in the 1970s. A genetic algorithm (GA) is stochastic beam search where successors are made by combining two parents, not by modifying one state.

The vocabulary

BiologyGABolt's knapsack (next code)
Individual / chromosomeOne candidate solution, encoded as a string20 bits: carry order \(i\) or not
GeneOne position in the stringone bit
AlleleA value a gene can take0 or 1
PopulationThe current set of candidates60 loading plans
FitnessObjective value (higher is better)total tips, if not overweight
GenerationOne iteration of the loop—
Genotype vs phenotypeEncoding vs what it meansbitstring vs the actual set of orders

The algorithm

function GENETIC-ALGORITHM(population, FITNESS):
    repeat:
        new_population ← elite (the best few, copied unchanged)      # optional elitism
        while |new_population| < N:
            x ← SELECT(population, FITNESS)          # fitter ⇒ more likely
            y ← SELECT(population, FITNESS)
            child ← CROSSOVER(x, y)   with prob p_c  (else copy a parent)
            child ← MUTATE(child)     each gene with small prob p_m
            add child to new_population
        population ← new_population
    until some individual is fit enough, or time/budget runs out
    return the best individual seen
populationgeneration t evaluatefitness f(x) selectparents crossovercombine mutateexplore new population = generation t+1 (plus elites)

Now let's look at each component properly. Each one is a design decision that can make a GA succeed or fail.

1. Representation (encoding)

How you encode a solution decides what crossover and mutation mean. Here are the common choices:

  • Binary strings: classic. Good for yes/no decisions (knapsack, feature selection). Numbers can be binary-encoded too: \(x \in \{0,\dots,31\}\) uses 5 bits.
  • Real-valued vectors: each gene is a float. This is natural for weights, as in the GA lab.
  • Permutations: orderings (routes for the travelling salesman). These need special operators, because ordinary crossover would visit some hostels twice and others never.
  • Integer strings: the 8-queens state "16257483" (row of each column's queen).

A good encoding puts related genes close together and ensures that small genotype changes give small phenotype changes. With plain binary, 7 = 0111 and 8 = 1000 differ in all 4 bits. Gray code fixes this, because neighbouring integers differ in exactly one bit.

2. Fitness

Fitness is the objective. Selection only uses comparisons or proportions of fitness, so the design questions are:

  • Constraints. What if a child is infeasible, such as an overloaded knapsack? Either repair it, or penalize it: fitness = value − (penalty × amount of violation).
  • What do you really want? In the lab, minimizing training error would evolve an overfit model, so fitness must include validation error. A GA optimizes exactly what you write, not what you mean. Remember the dirt-sucking vacuum from §1.1.
  • Cost. Fitness evaluation usually dominates the runtime (or, in the assignment, the query budget).

3. Selection

Selection decides who gets to reproduce. The core tension is selection pressure. Too little and the GA is a random search. Too much and the population fills with copies of one early-good individual (premature convergence), losing the diversity crossover needs.

Roulette-wheel (fitness-proportionate) selection

Individual \(i\) is chosen with probability \(p_i = f_i / \sum_j f_j\). Picture a roulette wheel where each individual's slice is proportional to its fitness.

Worked example: maximize \(f(x) = x^2\), \(x \in [0, 31]\), 5-bit encoding

This is the classic textbook example (Goldberg, 1989). Initial population:

#String\(x\)\(f(x)=x^2\)\(p_i = f_i/\sum f\)Expected copies \(N p_i\)
101101131690.1440.58
211000245760.4921.97
3010008640.0550.22
410011193610.3091.23
Σ = 1170, avg 292.51.0004.00

Suppose the four spins pick #1, #2, #2, #4. Pair them as (#1, #2) and (#2, #4), and apply one-point crossover:

  • 0110|1 × 1100|0 with the cut after bit 4 gives 01100 (12) and 11001 (25).
  • 11|000 × 10|011 with the cut after bit 2 gives 11011 (27) and 10000 (16).

New fitnesses: 144, 625, 729, 256. Sum = 1754, average 438.5, max 729 (up from 576). One generation raised the average fitness by 50%, without anyone "knowing" that bigger \(x\) is better.

Roulette has known problems:

  • It needs non-negative fitness. Shift the values, or use another method.
  • It is sensitive to scaling. If one individual has fitness 1000 and the rest have 10, it takes over immediately (premature convergence). Late in a run, when everyone has fitness 100 ± 1, selection is nearly uniform and the pressure is too low.

Tournament selection (the practical default)

Pick \(k\) individuals at random and return the best of them. \(k\) controls the pressure: \(k=1\) is random selection, and a large \(k\) is very greedy. Tournament selection only compares fitness values, so it doesn't care about scale or sign, and it is cheap and easy to parallelize. \(k = 2\) or \(3\) is common.

Rank selection and truncation

  • Rank selection: sort by fitness, and make the selection probability depend on rank, not raw fitness. This fixes the scaling problems.
  • Truncation selection: only the top \(\tau\)% (say 50%) may breed, uniformly. It's simple and strong, and it's what the lab code uses.

4. Crossover (recombination)

Crossover is what makes a GA more than parallel hill climbing. It combines good parts of different parents.

one-point (cut after 3) 111|11111 000|00000 11100000 00011111 two-point (cuts after 2, 5) 11|111|111 00|000|000 11000111 00111000 uniform (coin per gene) 11111111 00000000 10010110 01101001 parents ↑ · children ↓ Real-valued genes: arithmetic/blend crossover, child = α·parent₁ + (1−α)·parent₂
  • One-point: choose a cut point, swap the tails. It keeps contiguous blocks of genes together.
  • Two-point / k-point: swap the middle segment(s).
  • Uniform: each gene comes from either parent with probability ½. Lots of mixing, and it ignores gene order.
  • Arithmetic / blend (real genes): child \(= \alpha a + (1-\alpha) b\), a point on the line between the parents.
  • Order crossover (OX) (permutations): copy a slice from parent 1, then fill the rest in parent 2's order, skipping duplicates.

Crossover is applied with probability \(p_c\) (typically 0.6–0.95). Otherwise the parents are copied unchanged.

Intuition: building blocks and the schema theorem

Why should mixing two good solutions produce a better one? Holland's answer: good solutions contain short, useful building blocks, such as "genes 3–5 = 101" in the knapsack, meaning "carry these three light, high-tip orders together." A schema like **101*** describes all strings with that block. The schema theorem says that short, low-order schemata with above-average fitness get exponentially more copies in later generations. Selection amplifies them, and crossover rarely cuts short blocks apart. Crossover then assembles blocks from different parents. In the \(x^2\) example, parent 11000 has the good high bit and parent 10011 contributes low bits, and their child 11011 = 27 has both.

This is also why representation matters: if related genes are far apart, one-point crossover keeps cutting good combinations apart.

5. Mutation

Mutation makes small random changes:

  • Bit-flip: each bit flips with probability \(p_m\), commonly \(p_m = 1/L\) for string length \(L\) (one flip per child on average).
  • Gaussian: for real genes, add \(\mathcal{N}(0, \sigma^2)\) noise. Shrinking \(\sigma\) over time works like annealing.
  • Swap / inversion: for permutations.

Why do we need it? Selection and crossover only rearrange existing genetic material. If no individual has a 1 in position 4, crossover can never create one. Mutation keeps every allele reachable and restores lost diversity. Crossover exploits what the population already knows. Mutation explores.

6. Replacement and elitism

  • Generational: the children replace the whole population.
  • Steady-state: only a few individuals are replaced each step, usually the worst.
  • Elitism: copy the best \(e\) individuals unchanged into the next generation. The best fitness can then never decrease, which is cheap insurance. Keep \(e\) small (1–5%), or you'll lose diversity.

Play with it

The GA below evolves random strings toward a target sentence. Fitness is the number of characters in the right place. With 27 possible characters and 19 positions there are \(27^{19} \approx 1.6 \times 10^{27}\) strings, so random guessing would never succeed. Experiment:

  • Set mutation rate = 0. The GA stalls once some needed letter has vanished from the population.
  • Set mutation rate = 0.2. Too much noise destroys progress (a random walk).
  • Turn crossover off. It still works (it becomes mutation + selection, like parallel stochastic hill climbing), but more slowly.
  • Set tournament size = 1. With no selection pressure, nothing improves.

A real GA: Bolt's knapsack

Bolt can carry 35 kg. Twenty orders are waiting, each with a weight and a tip. Which subset maximizes the tips? With \(2^{20} \approx 10^6\) subsets this is still brute-forceable, which lets us check that the GA finds the true optimum. At 100 orders, brute force would be hopeless and a GA would still work fine.

import random

# Bolt's evening: which of 20 orders to carry? Each has a weight (kg) and a tip (rupees).
rng = random.Random(7)
weights = [rng.randint(1, 9) for _ in range(20)]
values  = [rng.randint(5, 60) for _ in range(20)]
CAPACITY = 35

def fitness(chrom):
    w = sum(wi for wi, g in zip(weights, chrom) if g)
    v = sum(vi for vi, g in zip(values, chrom) if g)
    return v if w <= CAPACITY else CAPACITY - w        # overweight => negative (infeasible)

def tournament(pop, fits, k=3):
    contenders = rng.sample(range(len(pop)), k)
    return pop[max(contenders, key=lambda i: fits[i])]

def crossover(a, b):                                    # one-point crossover
    cut = rng.randrange(1, len(a))
    return a[:cut] + b[cut:], b[:cut] + a[cut:]

def mutate(chrom, pm):                                  # independent bit flips
    return [1 - g if rng.random() < pm else g for g in chrom]

def genetic_algorithm(pop_size=60, generations=80, pc=0.9, pm=1/20, elite=2):
    pop = [[rng.randint(0, 1) for _ in range(20)] for _ in range(pop_size)]
    for gen in range(generations):
        fits = [fitness(c) for c in pop]
        ranked = sorted(range(pop_size), key=lambda i: fits[i], reverse=True)
        if gen % 20 == 0:
            print(f"gen {gen:3d}: best = {fits[ranked[0]]:4d}, mean = {sum(fits)/pop_size:7.1f}")
        new_pop = [pop[i] for i in ranked[:elite]]       # elitism: keep the best unchanged
        while len(new_pop) < pop_size:
            p1, p2 = tournament(pop, fits), tournament(pop, fits)
            c1, c2 = crossover(p1, p2) if rng.random() < pc else (p1[:], p2[:])
            new_pop += [mutate(c1, pm), mutate(c2, pm)]
        pop = new_pop[:pop_size]
    return max(pop, key=fitness)

best = genetic_algorithm()
print("GA best value:", fitness(best), "weight:", sum(w for w, g in zip(weights, best) if g))

# exact optimum by dynamic programming, to check the GA
dp = [0] * (CAPACITY + 1)
for w, v in zip(weights, values):
    for c in range(CAPACITY, w - 1, -1):
        dp[c] = max(dp[c], dp[c - w] + v)
print("true optimum    :", dp[CAPACITY])
gen   0: best =  303, mean =    49.9
gen  20: best =  408, mean =   247.6
gen  40: best =  408, mean =   230.3
gen  60: best =  408, mean =   249.9
GA best value: 408 weight: 35
true optimum    : 408

The GA hit the exact optimum (408) by generation 20, using \(20 \times 60 = 1200\) fitness evaluations instead of about a million. The mean fitness plateaus around 250 and not 408 because mutation keeps creating some infeasible children with negative fitness. That's the price of continued exploration, and it's healthy.

Tuning a GA: a practical cheat sheet

ParameterTypicalToo lowToo high
Population size \(N\)20–200Little diversity, premature convergenceSlow; wasted evaluations
Crossover rate \(p_c\)0.6–0.95Slow mixing of building blocks(Rarely harmful)
Mutation rate \(p_m\)\(1/L\)Stagnation, lost allelesRandom search, good solutions destroyed
Selection pressure (tournament \(k\))2–4Aimless driftPremature convergence
Elitism \(e\)1–5% of \(N\)Best solution can be lostPopulation dominated by elites
Premature convergence: the #1 GA failure

Symptoms: the population's average fitness catches up with the best within a few generations, then nothing improves. All individuals look alike. Fixes: lower selection pressure, raise mutation, use a larger population, inject random immigrants, or keep sub-populations separate (the "island model").

GA vs SA vs hill climbing

  • GAs shine when good solutions are made of combinable parts (building blocks) and the landscape is rugged.
  • If there's no meaningful way to combine two solutions, crossover is just a big random mutation, and SA or restarts may be just as good and simpler.
  • GAs need many fitness evaluations. When evaluations are expensive (as with a rate-limited server), you have to use them cleverly: small populations, good initialization and caching.
Exam corner: what to practise by hand
  • Compute roulette probabilities and expected copies \(N p_i\).
  • Apply one-point / two-point / uniform crossover at given cut points.
  • Apply mutation at given positions and recompute fitness.
  • Explain why mutation is necessary (lost alleles) and why crossover helps (building blocks).
  • AIMA's 8-queens GA: fitness = number of non-attacking pairs (max \(\binom{8}{2}=28\)). Values 24, 23, 20, 11 give selection probabilities 24/78 = 31%, 29%, 26%, 14%.