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 says whether item is packed, and the fitness is the packed value if the weight limit holds and 0 otherwise1.
The loop1:
- Create an initial population (usually random).
- Evaluate fitness; select parents, fitter ones more often.
- Crossover (recombination) mixes two parents into children.
- Mutation randomly changes genes of a child.
- 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.
| Method | Rule | Notes |
|---|---|---|
| Roulette wheel | needs ; one dominant individual takes over | |
| Stochastic universal sampling | one spin, pointers apart | same expectations, minimal spread |
| Linear rank | for rank (1 = best) | uses only the ordering |
| Tournament | draw , keep the fittest | larger = higher pressure; 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 positions give 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 holds the city after ) and ordinal (indices into a shrinking reference list).
Mutation5: bit-flip with probability per bit, commonly (about one flip per child). With 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 and each ant adds to every edge of its tour, so shorter tours ( small) leave more pheromone7.
Formulas
Schema (e.g. 1**0*1**): order = number of fixed positions, defining length
= distance between the first and last fixed positions; it matches strings6.
Holland's schema theorem6:
Short, low-order, above-average schemata grow exponentially6. Probability a child of length survives bit-flip mutation unchanged: , which is for .
Worked example
Fitness 5, 3, 2 (total 10). Roulette: ; a mating pool of 3 expects copies of the best. Deterministic tournament, , with replacement: the best wins iff it is drawn at least once, .
Schema 1**0*1** (): fixed positions 1, 4, 6, so , , matching strings.
With , : . If and , the bound
is : 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
- Crossover vs mutation: crossover needs two parents and recombines; mutation alters one individual randomly1.
- Pass/fail fitness stalls the search — there is no gradient of quality to follow1.
- Plain one-point crossover on path-encoded tours gives invalid tours; use PMX, OX1 or CX4.
- More selection pressure is not always better: it speeds convergence but risks premature convergence2.
- A larger tournament raises pressure (weak individuals meet stronger ones more often)3.
- Defining length counts the distance, not the number of fixed positions: for
*10***1*the fixed positions are 2, 3, 7, so but 6. - High mutation is not "more exploration for free": at inheritance is lost entirely.
References
- Wikipedia: Genetic algorithm — Methodology (Optimization problems; Initialization; Selection; Genetic operators; Termination); Limitations; Variants (Elitism); Problem domains
- Wikipedia: Selection (evolutionary algorithm) — Methods of selection (Roulette wheel selection; Stochastic universal sampling; Rank selection; Linear rank selection; Elitist selection)
- Wikipedia: Tournament selection — Introduction; Variants
- Wikipedia: Crossover (evolutionary algorithm) — Crossover for binary arrays; Crossover for permutations (PMX; Order crossover (OX1); Further crossover operators)
- Wikipedia: Mutation (evolutionary algorithm) — Introduction; Bit string mutation; Mutation of permutations
- Wikipedia: Holland's schema theorem — Introduction; Description
- Wikipedia: Ant colony optimization algorithms — Algorithm and formula (Edge selection; Pheromone update)