Overview

7 Genetic Algorithm

This chapter introduces genetic algorithms as a central member of population-based metaheuristics, contrasting their multi-agent, exploration-oriented search with single-trajectory, exploitation-heavy methods. It classifies population metaheuristics into evolutionary computation and swarm intelligence, focusing on the former as the conceptual foundation of GAs. A strong emphasis is placed on how the diversity and quality of the initial population shape performance, surveying practical sampling strategies—pseudo- and quasi-random sequences, Sobol and Latin hypercube designs, and Gaussian-inspired methods—to balance exploration and exploitation from the outset.

Building on biological evolution, the chapter distills evolutionary computation into five core components: a population of candidate solutions, a fitness function, parent selection, genetic operators (crossover and mutation), and survival strategies. It surveys major EC paradigms (GA, DE, GP, EP, ES, CA, and co-evolution) and discusses advantages (domain-agnostic flexibility, interpretability, multiple alternatives, and natural parallelism) alongside limitations (computational cost, tuning needs, and lack of optimality guarantees). Practical GA design choices are covered in depth: encoding schemes (binary, real, permutation), transforming minimization to maximization, and selection with calibrated selective pressure (elitism, fitness-proportionate/roulette, rank-based linear and non-linear, stochastic universal sampling, tournament, and random). Survivor selection and population update models (generational vs steady-state) complete the algorithmic picture.

The chapter then operationalizes GA: initialize a population, evaluate fitness, select parents, recombine via 1-point, n-point, or uniform crossover, inject diversity with mutation, repair infeasible offspring when needed, and terminate on common criteria (evaluation budget, threshold attainment, stagnation, or resource limits). A binary-coded case study (ticket pricing) demonstrates end-to-end design—from bit-length determination and sampling to selection, reproduction, and survivor choice—showing GA converging to the same solution as a classical optimizer. Implementation is presented both from scratch in Python and with a modern framework (pymoo), highlighting practical elements such as sampling operators, crossover/mutation choices, feasibility repair, duplicate elimination, and parameterization (population size, probabilities). The result is a clear, hands-on blueprint for applying GAs to discrete and continuous optimization problems.

Metaheuristics algorithms
Sampling methods to generate initial population
Generate random initial routes
Genotype, phenotype and taxonomic classification
EC Paradigms
Genetic Algorithm versus Natural Evolution
GA Steps
Equation 7.1
Equation 7.2
Binary Encoding
Selection methods with their selective pressure
Equation 7.4
Roulette wheel of ticket pricing example
Equation 7.5
Equation 7.6
Stochastic Universal Sampling (SUS) strategy
Tournament Selection
1-point crossover
n-point crossover
Uniform Crossover
Mutation
GA generational and steady-state models

Summary

  • Metaheuristic algorithms that are population-based, often referred to as P-metaheuristics, employ multiple agents to find an optimal or near-optimal global solution. These algorithms can be divided into two main categories, depending on their source of inspiration: evolutionary computation algorithms and swarm intelligence algorithms.
  • Evolutionary computation algorithms draw inspiration from the process of biological evolution. Examples of evolutionary computation algorithms include Genetic Algorithm (GA), Differential Evolution (DE), Genetic Programming (GP), Evolutionary Programming (EP), Evolutionary Strategies (ES), Cultural Algorithms (CA), and Co-evolution (CoE).
  • The genetic algorithm is the most widely used form of evolutionary computation. It is an adaptive heuristic search method designed to mimic the natural system’s processes required for evolution, as outlined in Charles Darwin's theory of evolution.
  • Pseudo-random, Quasi-random, Sequential diversification, Parallel diversification, and heuristics represent various initialization strategies for P-metaheuristics like genetic algorithms. Each strategy offers distinct levels of diversity, computational cost, and initial solution quality.
  • In genetic algorithms, the crossover and mutation operators play essential roles in searching the solution space and maintaining diversity within the population. The primary purpose of these operators is to handle the search dilemma by balancing exploration/diversification (searching new areas of the solution space) and exploitation/intensification (refining the existing solutions).
  • High crossover rate and a low mutation rate are recommended to balance exploration and exploitation. The high crossover rate facilitates the sharing of good traits between individuals, while the low mutation rate introduces small random changes to maintain diversity and prevent premature convergence. This combination allows the algorithm to efficiently search the solution space and find high-quality solutions.
  • In the generational model of genetic algorithms, the entire population is replaced while in the steady-state model of genetic algorithms, a small fraction of the population is replaced. The steady-state model has lower computation cost compared to the generational model in genetic algorithms but generational models improves diversity preservation compared to the steady-state models.
  • A wide range of open-source Python libraries exist for working with genetic algorithms. One such library, pymoo (Multi-objective Optimization in Python), includes popular algorithms such as genetic algorithms, differential evolution, evolutionary strategies, Non-dominated Sorting Genetic Algorithm (NSGA-II), NSGA-III, and Particle Swarm Optimization (PSO).

FAQ

What are population-based metaheuristics and why use them?They use many candidate solutions (a population) to explore the search space in parallel, which encourages exploration and reduces the chance of getting trapped in poor local optima. Two main families exist: evolutionary computation (e.g., GA, DE, GP, ES) inspired by biological evolution, and swarm intelligence (e.g., PSO, ACO, ABC) inspired by collective animal behavior. Compared to single-trajectory methods, they trade higher computational cost for stronger global search capability and robustness.
What is a Genetic Algorithm (GA) and when is it a good choice?GA is an evolutionary optimizer that iterates over populations of candidate solutions using selection, crossover (recombination), and mutation to improve fitness. It works well for black-box, nonlinear, noisy, mixed discrete/continuous, and combinatorial problems. Pros: generality, transparency, parallelism, multiple alternatives. Cons: no finite-time optimality guarantee, parameter tuning needed, potentially costly.
What are the core components of a GA?- A population of individuals (candidate solutions) - A fitness function (usually formulated as a maximization) - Parent selection (e.g., roulette, rank-based, tournament) - Genetic operators: crossover (combine parents) and mutation (introduce variation) - Survivor selection (replacement strategy) - Termination criteria (e.g., max generations, time, target fitness, or no improvement)
How do I create a good initial population?Diversity early on helps avoid premature convergence. Common strategies: - Pseudo-random sampling: simple, diverse, low-quality initial solutions. - Quasi-random/low-discrepancy (Halton, Sobol): more uniform coverage than pseudo-random. - Latin Hypercube Sampling (LHS): stratifies each dimension to spread points across space. - Box–Muller and CLT-based sampling: generate (approx.) normal distributions when appropriate. Pick methods that balance diversity and cost; quasi-random and LHS often give better space coverage.
How do I handle minimization objectives in GA (which prefers maximization)?Convert the objective O(x) into a maximization fitness f(x). Options: - Negation: f(x) = −O(x) (simple and general). - Reciprocal: f(x) = 1/(O(x)+ε) if values are nonnegative and ε avoids division by zero. - Shift/scale transforms: add a large constant or use rank-based fitness to ensure nonnegative, well-scaled fitness. Note: Libraries like pymoo assume minimization; negate the original objective or define it accordingly.
Which representation should I use (binary, real-valued, permutation), and how many bits are needed?- Binary-coded GA (BGA): encode variables as bit strings (simple operators, good for discrete or coarse continuous). - Real-valued GA: operate directly on floats (often better for continuous optimization). - Permutation encoding: for ordering problems (e.g., routes, schedules). Bits needed for a bounded scalar with precision p: 1) Steps = ceil((UB − LB)/p) 2) Bits = ceil(log2(Steps)) Example: 75–235 with precision 1 → 160 steps → 8 bits; with precision 0.1 → 1600 steps → 11 bits.
What parent selection methods exist and what is selective pressure?Selective pressure is how strongly the fitter individuals are favored. Too high → premature convergence; too low → slow progress. Common methods: - Elitism (preserve top individuals; very high pressure as a survivor strategy). - Fitness-proportionate (roulette): probability ∝ fitness; can over-favor elites. - Rank-based: uses ranks instead of raw fitness to moderate pressure; tunable. - Stochastic Universal Sampling (SUS): reduces sampling variance vs roulette. - Tournament: draw k competitors, pick the best; k controls pressure. - Random: lowest pressure, maintains diversity but weak selection.
How do crossover and mutation work in BGA, and how do I keep solutions feasible?- Crossover: combine parents to create offspring. Variants include 1-point, n-point, and uniform crossover (bit-wise mixing). - Mutation: flip each bit with small probability p_m to maintain diversity. Feasibility: after reproduction, check constraints. Options include repairing out-of-bounds solutions, resampling, or rejecting invalid offspring. In pymoo, use repair operators (e.g., RoundingRepair) to enforce bounds.
What is the difference between generational and steady-state GA? How does survivor selection work?- Generational: replace the entire population with offspring each generation. - Steady-state: insert a few offspring and remove some existing individuals each iteration. Survivor selection options include random, age-based (FIFO), fitness-based (elitism or delete worst), and tournament. Generational can accelerate change; steady-state can preserve diversity and enable smoother progress.
How do I implement a simple binary GA in Python from scratch?Typical steps: 1) Initialize population (random bit strings). 2) Evaluate fitness for all individuals. 3) Select parents (e.g., random, roulette, or tournament). 4) Apply crossover with probability p_c. 5) Apply mutation to bits with probability p_m. 6) Form the next population (survivor selection). 7) Repeat until termination criteria are met. Typical starting ranges: pop_size 50–200+, p_c 0.6–0.9, p_m ≈ 1/num_bits to 0.1–0.3, 50–500+ generations; tune empirically.
How do I solve the ticket pricing example with pymoo, and what parameters matter?Define a Problem with bounds [75, 235] and set the objective for minimization (e.g., minimize −profit or rewrite the function). Configure GA with: - Population size (e.g., 100). - Sampling (FloatRandomSampling or LHS). - Crossover (PointCrossover with n_points=1 or 2, prob≈0.8). - Mutation (PolynomialMutation with prob≈0.1–0.3 and a repair operator to keep feasibility). - eliminate_duplicates=True to maintain diversity. Call minimize with (n_gen, …) and a seed for reproducibility. The setup recovers the known optimal price (~$155 in the example) and profit.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Optimization Algorithms ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Optimization Algorithms ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Optimization Algorithms ebook for free