Genetic Algorithms

GATE Relevance: Low-Medium

Prerequisites

🎯 Learning Objectives

  • Understand the GA framework: population, fitness, selection, crossover, mutation
  • Compare encoding schemes: binary and permutation
  • Apply selection methods: roulette wheel, tournament
  • Implement crossover and mutation operators
  • Write GA pseudocode
  • Understand the Schema Theorem (basics)
  • Solve the 8-queens problem with a GA

1. Overview

A Genetic Algorithm (GA) is a population-based search method inspired by natural evolution. Instead of improving a single state (like hill climbing or SA), a GA maintains a population of candidate solutions and evolves them over generations using operators inspired by biology: selection, crossover (recombination), and mutation.

Core Idea

Survival of the fittest: good solutions are more likely to be selected as parents. Crossover combines parts of two parents to create offspring that may inherit good traits from both. Mutation introduces random variation to maintain diversity and escape local optima.

GAs were popularized by John Holland in the 1970s and have been applied to scheduling, design optimization, neural network training, game playing, and many other domains.

1.1 GA vs Other Local Search Methods

  • Hill climbing / SA: single-state search. GA: population-based (parallel exploration).
  • SA: escapes local optima via random bad moves. GA: escapes via crossover and diversity.
  • GA strength: combines building blocks from different solutions (crossover).
  • GA weakness: many parameters to tune; slower per generation; no optimality guarantee.

2. Encoding (Representation)

Each candidate solution is represented as a chromosome (or individual). The encoding determines how solutions are represented as strings that the GA operators can manipulate.

2.1 Binary Encoding

The most common encoding. Each chromosome is a binary string of fixed length.

Example: Maximize f(x) where x ∈ [0, 31].
Encoding: 5-bit binary string.
  x = 13  →  chromosome: [0, 1, 1, 0, 1]
  x = 25  →  chromosome: [1, 1, 0, 0, 1]

2.2 Permutation Encoding

Used for ordering problems (e.g., TSP, N-Queens).

8-Queens: chromosome = [3, 1, 6, 2, 8, 4, 7, 5]
  Meaning: queen in column 1 is in row 3,
           queen in column 2 is in row 1, etc.

2.3 Other Encodings

  • Integer encoding — each gene is an integer (e.g., for feature selection)
  • Real-valued encoding — each gene is a floating-point number (for continuous optimization)
  • Tree encoding — used in genetic programming (evolving programs)

3. Fitness Function

The fitness function evaluates how good a chromosome is. It maps each individual to a non-negative real number. Higher fitness = better solution.

Fitness Examples
  • Maximization of f(x): fitness = f(x) (directly)
  • 8-Queens: fitness = 28 − (number of attacking pairs). Max fitness = 28 (no attacks among 8 queens: C(8,2) = 28 pairs, all non-attacking).
  • TSP: fitness = 1 / tour_length (shorter tour = higher fitness)

4. Selection Methods

Selection determines which individuals become parents for the next generation. Fitter individuals should have a higher chance of being selected.

4.1 Roulette Wheel Selection (Fitness-Proportionate)

Each individual gets a “slice” of a roulette wheel proportional to its fitness. Spin the wheel to select a parent.

Population (4 individuals):
  A: fitness = 10   →  P(A) = 10/(10+20+30+40) = 10/100 = 0.10
  B: fitness = 20   →  P(B) = 20/100 = 0.20
  C: fitness = 30   →  P(C) = 30/100 = 0.30
  D: fitness = 40   →  P(D) = 40/100 = 0.40

Cumulative: A=[0, 0.10], B=(0.10, 0.30], C=(0.30, 0.60], D=(0.60, 1.00]
Random number 0.45 → selects C.
Random number 0.85 → selects D.

⚠ Problem with Roulette Wheel

If one individual has very high fitness compared to others, it dominates selection (premature convergence). If all fitnesses are similar, selection is nearly random (slow convergence). Scaling or ranking can mitigate this.

4.2 Tournament Selection

Randomly pick k individuals (a “tournament”). The fittest of the k wins and becomes a parent. Repeat for each parent needed.

Tournament size k = 3:
  Randomly pick B (fitness 20), D (fitness 40), A (fitness 10).
  Winner: D (highest fitness).

Tournament size k = 2:
  Randomly pick A (fitness 10), C (fitness 30).
  Winner: C.

Advantages: Simple, no need to compute total fitness, adjustable selection pressure via k.

4.3 Comparison

MethodSelection PressureComplexityNotes
Roulette WheelProportional to fitnessO(n)Can cause premature convergence
Tournament (k)Adjustable via kO(k) per selectionMost commonly used in practice
Rank SelectionBased on rank, not fitness valueO(n log n)Avoids fitness scaling issues
ElitismTop individuals surviveO(n log n)Used alongside other methods

5. Crossover Operators

Crossover combines two parent chromosomes to produce offspring. It is the primary mechanism for exploring new regions of the search space.

5.1 Single-Point Crossover

Choose a random crossover point. Offspring 1 gets parent 1’s genes before the point and parent 2’s genes after. Offspring 2 gets the reverse.

Parent 1: [1 0 1 | 1 0 0 1]    crossover point after position 3
Parent 2: [0 1 0 | 0 1 1 0]

Child 1:  [1 0 1 | 0 1 1 0]    (P1 left + P2 right)
Child 2:  [0 1 0 | 1 0 0 1]    (P2 left + P1 right)

5.2 Two-Point Crossover

Choose two random crossover points. The segment between them is swapped.

Parent 1: [1 0 | 1 1 0 | 0 1]    points at positions 2 and 5
Parent 2: [0 1 | 0 0 1 | 1 0]

Child 1:  [1 0 | 0 0 1 | 0 1]   (P1 outer + P2 middle)
Child 2:  [0 1 | 1 1 0 | 1 0]   (P2 outer + P1 middle)

5.3 Uniform Crossover

For each gene position, randomly choose which parent contributes (e.g., flip a coin).

Parent 1: [1 0 1 1 0 0 1]
Parent 2: [0 1 0 0 1 1 0]
Mask:     [1 0 1 0 0 1 0]   (1 = take from P1, 0 = take from P2)

Child:    [1 1 1 0 1 0 0]

5.4 Order Crossover (OX) — for Permutations

Used when chromosomes are permutations (e.g., TSP, N-Queens). Standard crossover would produce invalid permutations (repeated values).

Parent 1: [3 1 6 | 2 8 4 | 7 5]    segment [2, 8, 4]
Parent 2: [5 4 2 | 7 1 3 | 8 6]

Step 1: Copy segment from P1 to child:
  Child:  [_ _ _ | 2 8 4 | _ _]

Step 2: Fill remaining positions with P2's order (skip already used):
  P2 order: 5, 4, 2, 7, 1, 3, 8, 6  →  remove {2, 8, 4}  →  5, 7, 1, 3, 6
  Fill from after segment: positions 7,8,1,2,3:
  Child:  [1 3 6 | 2 8 4 | 5 7]

6. Mutation Operators

Mutation introduces small random changes to maintain genetic diversity and prevent premature convergence. It applies with a small probability (typically 0.001 – 0.05 per gene).

6.1 Bit-Flip Mutation (Binary Encoding)

Before: [1 0 1 1 0 0 1]
                    ^         (mutation at position 3)
After:  [1 0 0 1 0 0 1]

6.2 Swap Mutation (Permutation Encoding)

Before: [3 1 6 2 8 4 7 5]
Swap positions 2 and 5:
After:  [3 8 6 2 1 4 7 5]

6.3 Inversion Mutation (Permutation)

Before: [3 1 6 2 8 4 7 5]
Reverse segment [positions 3-6]:
After:  [3 1 4 8 2 6 7 5]

6.4 Gaussian Mutation (Real-Valued)

Add a random value from a Gaussian distribution N(0, σ) to a gene.

7. GA Pseudocode

function GENETIC-ALGORITHM(problem, pop_size, p_crossover, p_mutation, max_gen):
    // Initialize random population
    population = [RANDOM-INDIVIDUAL() for i in 1..pop_size]

    for generation = 1 to max_gen:
        // Evaluate fitness
        fitnesses = [FITNESS(individual) for individual in population]

        // Check termination
        best = individual with max fitness
        if FITNESS(best) == optimal_fitness:
            return best

        // Create new population
        new_population = []

        // Elitism: keep the best individual(s)
        new_population.add(best)

        while |new_population| < pop_size:
            // Selection
            parent1 = SELECT(population, fitnesses)
            parent2 = SELECT(population, fitnesses)

            // Crossover
            if RANDOM() < p_crossover:
                child1, child2 = CROSSOVER(parent1, parent2)
            else:
                child1, child2 = parent1, parent2

            // Mutation
            child1 = MUTATE(child1, p_mutation)
            child2 = MUTATE(child2, p_mutation)

            new_population.add(child1)
            if |new_population| < pop_size:
                new_population.add(child2)

        population = new_population

    return best individual in final population

📝 Typical Parameter Values

  • Population size: 50 – 200
  • Crossover probability: 0.6 – 0.9
  • Mutation probability: 0.001 – 0.05 per gene
  • Tournament size: 2 – 7
  • Elitism: keep top 1 – 5 individuals

8. Schema Theorem (Basics)

Holland’s Schema Theorem provides a theoretical foundation for why GAs work. A schema is a template with fixed and wildcard (*) positions.

Schema: [1 * 0 * 1 * 0]
Matches: [1 0 0 0 1 0 0], [1 1 0 1 1 1 0], etc.

Defining length δ(H) = distance between first and last fixed positions.
  For [1 * 0 * 1 * 0]: first fixed = position 1, last = position 7. δ = 6.

Order o(H) = number of fixed positions.
  For [1 * 0 * 1 * 0]: o = 4.

Schema Theorem (Informal)

Short, low-order schemas with above-average fitness increase exponentially in frequency across generations. These are called building blocks. GAs work by assembling good building blocks into complete solutions.

Formally: E[m(H, t+1)] ≥ m(H, t) · f(H)/f̅ · [1 − pc·δ(H)/(L−1)] · [1 − pm]o(H)

where m(H,t) = number of individuals matching schema H at generation t, f(H) = average fitness of schema H, f̅ = population average fitness, L = chromosome length.

Implications:

  • Above-average schemas grow; below-average schemas shrink.
  • Short schemas (small δ) are less likely to be disrupted by crossover.
  • Low-order schemas (small o) are less likely to be disrupted by mutation.
  • GAs implicitly evaluate an exponential number of schemas in polynomial time (“implicit parallelism”).

9. 8-Queens with a Genetic Algorithm

9.1 Setup

  • Encoding: permutation [r₁, r₂, …, r₈] — queen in column i is in row rᵢ
  • Fitness: 28 − (attacking pairs). Goal: fitness = 28.
  • Selection: tournament (k=3)
  • Crossover: order crossover (OX)
  • Mutation: swap mutation (swap two random positions), pm = 0.05
  • Population size: 8
Generation 0 (Initial Population)
Individual  Chromosome         Attacks  Fitness
   A        [5, 3, 1, 6, 8, 2, 4, 7]    2       26
   B        [3, 6, 2, 7, 1, 4, 8, 5]    3       25
   C        [8, 2, 4, 1, 7, 5, 3, 6]    1       27
   D        [2, 5, 7, 4, 1, 8, 6, 3]    4       24
   E        [4, 7, 3, 8, 2, 5, 1, 6]    2       26
   F        [1, 4, 6, 3, 5, 8, 2, 7]    3       25
   G        [6, 1, 5, 2, 8, 3, 7, 4]    2       26
   H        [7, 8, 2, 5, 3, 1, 6, 4]    5       23
Selection & Crossover (One Pair)

Tournament 1 (k=3): pick C (27), D (24), H (23). Winner: C [8,2,4,1,7,5,3,6].

Tournament 2 (k=3): pick A (26), E (26), B (25). Winner: A [5,3,1,6,8,2,4,7].

Order Crossover (positions 3–5 from C):

Parent C: [8 2 | 4 1 7 | 5 3 6]    copy segment [4, 1, 7]
Parent A: [5 3 | 1 6 8 | 2 4 7]

Child: [_ _ | 4 1 7 | _ _ _]
A's order (skip 4,1,7): 5, 3, 6, 8, 2
Fill: positions 6,7,8,1,2 → [8 2 | 4 1 7 | 5 3 6]
Hmm, let me recalculate:
  Remaining from A's order: 5, 3, 6, 8, 2
  Fill after segment: pos 6→5, pos 7→3, pos 8→6, pos 1→8, pos 2→2
  Child: [8 2 | 4 1 7 | 5 3 6]  (same as C in this case!)

With different crossover points, more mixing occurs.
Mutation
Child before mutation: [8, 2, 4, 1, 7, 5, 3, 6]
Swap mutation (positions 1 and 6):
Child after mutation:  [5, 2, 4, 1, 7, 8, 3, 6]
New attacks: 3, fitness = 25 (worse, but adds diversity)

After many generations, the population converges toward fitness 28 (zero attacking pairs). Typical GAs solve 8-queens in 10–50 generations with population size 100.

10. Comparison with Other Local Search Methods

PropertyHill ClimbingSimulated AnnealingGenetic Algorithm
States maintained11Population (many)
Escapes local optima?No (except random restart)Yes (temperature)Yes (crossover + diversity)
Key mechanismBest neighborAccept bad moves probabilisticallyCombine good building blocks
MemoryO(1)O(1)O(pop_size × chromosome_length)
ParametersNoneT₀, αpop_size, p_c, p_m, selection, etc.
Parallelizable?NoNoYes (evaluate population in parallel)
Best forSimple/fast baselineSingle-objective continuousComplex, multi-modal, combinatorial

Summary

  • GAs maintain a population of candidate solutions and evolve them over generations.
  • Encoding: binary, permutation, real-valued, etc.
  • Selection: roulette wheel (fitness-proportionate) or tournament (most common).
  • Crossover: single-point, two-point, uniform (binary); order crossover (permutation). Primary exploration mechanism.
  • Mutation: bit-flip (binary), swap/inversion (permutation). Maintains diversity.
  • Schema Theorem: short, low-order, above-average schemas grow exponentially — GAs combine building blocks.
  • GAs are versatile but require careful parameter tuning and are slower per iteration than single-state methods.
  • GATE focus: understand operators, compute fitness, apply roulette wheel selection, trace one generation.

References

  • Holland, J.H. (1975). Adaptation in Natural and Artificial Systems.
  • Goldberg, D.E. (1989). Genetic Algorithms in Search, Optimization, and Machine Learning.
  • Russell & Norvig, Artificial Intelligence: A Modern Approach, 4th Ed. — Section 4.1.4.