Skip to content
ml-recall

Topic notes

Genetic Algorithms

Genetic algorithms evolve a population of encoded solutions by fitness-based selection, crossover and mutation; this note covers the loop, the operators and the schema theorem.

4-min read AI-checked

Practise 31 questions Take a test

Key ideas

A genetic algorithm (GA) is a population-based search inspired by evolution. It needs two things: an encoding of candidate solutions as chromosomes (genes, often bit strings) and a fitness function that scores them — e.g. scheduling, knapsack or TSP tours1. For the 0/1 knapsack, bit ii says whether item ii is packed, and the fitness is the packed value if the weight limit holds and 0 otherwise1.

The loop1:

  1. Create an initial population (usually random).
  2. Evaluate fitness; select parents, fitter ones more often.
  3. Crossover (recombination) mixes two parents into children.
  4. Mutation randomly changes genes of a child.
  5. Form the next generation (optionally keep the best unchanged: elitism2); stop after a fixed number of generations, a good-enough solution or a fitness plateau.

Only elitism guarantees that the best fitness never drops from one generation to the next; a loop that replaces the whole population by mutated children can lose its best individual1.

Why both operators. Crossover combines building blocks of different parents, and this mixing helps the population leave local optima where a hill climber would stop; mutation keeps diversity 1,5. A GA without crossover — selection plus random mutation — is essentially a set of stochastic hill climbers run in parallel. Standard crossovers cannot change a population in which all individuals are identical; only mutation can1. A mutation rate that is too low lets the population drift and stagnate; one that is too high destroys good solutions unless elitism keeps them1.

Fitness design. A pass/fail fitness (1 if the whole task is solved, else 0) gives a flat landscape with "no hill to climb": every random start scores 0, and the GA is no better than random search1. Give partial credit (e.g. the fraction of test cases handled correctly), and include cases that must be rejected, or the evolved solution may simply accept everything.

Selection2,3:

Method Rule Notes
Roulette wheel pi=fi/∑jfjp_i=f_i/\sum_j f_j needs f≥0f\ge 0; one dominant individual takes over
Stochastic universal sampling one spin, NN pointers ∑f/N\sum f/N apart same expectations, minimal spread
Linear rank P(i)=2(n−i+1)n(n+1)P(i)=\dfrac{2(n-i+1)}{n(n+1)} for rank ii (1 = best) uses only the ordering
Tournament draw kk, keep the fittest larger kk = higher pressure; k=1k=1 is random selection

Selection pressure: the higher it is, the faster the population converges — too high causes premature convergence to a suboptimal solution2. Tournament and rank selection depend only on which individual is fitter, so adding a constant to all fitness values changes nothing; roulette probabilities do change.

Crossover4: one-point (swap tails after a random cut), two-/k-point, uniform (each gene from either parent with probability 1/2; parents that differ in mm positions give 2m2^m possible children). For permutations (TSP tours) these break validity — a child may contain a city twice and miss another — so special operators are used: PMX (copy a segment, repair the rest through the segment's mapping), OX1 (copy a segment, fill the gaps in the other parent's order), cycle crossover (each position keeps a parent's value; positions are split into cycles). Other tour encodings: adjacency (position ii holds the city after ii) and ordinal (indices into a shrinking reference list).

Mutation5: bit-flip with probability pmp_m per bit, commonly pm=1/lp_m=1/l (about one flip per child). With pm=0.5p_m=0.5 every child is a uniformly random string — the GA degrades to random search. Permutations use swap, inversion or rotation5.

Ant colony optimisation (a related swarm method for the TSP): each ant builds a tour edge by edge, preferring edges with more pheromone and shorter length; afterwards pheromone evaporates by a factor 1−ρ1-\rho and each ant adds Q/LkQ/L_k to every edge of its tour, so shorter tours (LkL_k small) leave more pheromone7.

Formulas

Schema HH (e.g. 1**0*1**): order o(H)o(H) = number of fixed positions, defining length δ(H)\delta(H) = distance between the first and last fixed positions; it matches 2#∗2^{\#*} strings6. Holland's schema theorem6:

E[m(H,t+1)] ≥ m(H,t) f(H)at (1−p),p=δ(H)l−1 pc+o(H) pm\mathbb{E}[m(H,t+1)]\ \ge\ \frac{m(H,t)\,f(H)}{a_t}\,(1-p),\qquad p=\frac{\delta(H)}{l-1}\,p_c+o(H)\,p_m

Short, low-order, above-average schemata grow exponentially6. Probability a child of length ll survives bit-flip mutation unchanged: (1−pm)l(1-p_m)^l, which is ≈e−1≈0.37\approx e^{-1}\approx 0.37 for pm=1/lp_m=1/l.

Worked example

Fitness 5, 3, 2 (total 10). Roulette: P=0.5,0.3,0.2P=0.5, 0.3, 0.2; a mating pool of 3 expects 3×0.5=1.53\times0.5=1.5 copies of the best. Deterministic tournament, k=2k=2, with replacement: the best wins iff it is drawn at least once, 1−(2/3)2=5/9≈0.561-(2/3)^2=5/9\approx0.56.

Schema 1**0*1** (l=8l=8): fixed positions 1, 4, 6, so o=3o=3, δ=5\delta=5, 25=322^5=32 matching strings. With pc=0.7p_c=0.7, pm=0.01p_m=0.01: p=57(0.7)+3(0.01)=0.53p=\tfrac57(0.7)+3(0.01)=0.53. If m=10m=10 and f(H)/at=1.2f(H)/a_t=1.2, the bound is 10×1.2×0.47=5.64<1010\times1.2\times0.47=5.64<10: although the schema is fitter than average, the theorem no longer promises growth, because crossover disrupts such a long schema too often.

In code

def ox1(p0, p1, i, j):          # keep p0[i:j], fill the rest in p1's order
    child = [None] * len(p0)
    child[i:j] = p0[i:j]
    rest = [g for g in p1 if g not in child]
    for k in range(len(p0)):
        if child[k] is None:
            child[k] = rest.pop(0)
    return child

print("".join(ox1(list("ABCDEFGH"), list("HGFEDCBA"), 2, 5)))   # HGCDEFBA

Common pitfalls

References

  1. Wikipedia: Genetic algorithm — Methodology (Optimization problems; Initialization; Selection; Genetic operators; Termination); Limitations; Variants (Elitism); Problem domains
  2. Wikipedia: Selection (evolutionary algorithm) — Methods of selection (Roulette wheel selection; Stochastic universal sampling; Rank selection; Linear rank selection; Elitist selection)
  3. Wikipedia: Tournament selection — Introduction; Variants
  4. Wikipedia: Crossover (evolutionary algorithm) — Crossover for binary arrays; Crossover for permutations (PMX; Order crossover (OX1); Further crossover operators)
  5. Wikipedia: Mutation (evolutionary algorithm) — Introduction; Bit string mutation; Mutation of permutations
  6. Wikipedia: Holland's schema theorem — Introduction; Description
  7. Wikipedia: Ant colony optimization algorithms — Algorithm and formula (Edge selection; Pheromone update)