Genetic Algorithms: Representations and Experiments

CSI 4106 Introduction to Artificial Intelligence

Marcel Turcotte

Version: Nov 22, 2026 16:53

Preamble

Message of the Day

From a Complete GA to Its Design Choices

Learning Objectives

  • Explain how representation constrains the design of crossover and mutation.
  • Compare roulette and tournament selection, including the effect of tournament size.
  • Trace uniform crossover and circular-fill Order-1 crossover (OX1).
  • Distinguish per-gene bit mutation from per-offspring inversion mutation.
  • Interpret repeated-run comparisons under explicit computational budgets.
  • Assess GA results against appropriate baselines and relate them to simulated annealing.

Python Helpers from Lecture 20

Code
import numpy as np
import matplotlib.pyplot as plt

values = np.array([
    360, 83, 59, 130, 431, 67, 230, 52, 93, 125, 670, 892, 600, 38, 48, 147,
    78, 256, 63, 17, 120, 164, 432, 35, 92, 110, 22, 42, 50, 323, 514, 28,
    87, 73, 78, 15, 26, 78, 210, 36, 85, 189, 274, 43, 33, 10, 19, 389, 276,
    312])

weights = np.array([
    7, 0, 30, 22, 80, 94, 11, 81, 70, 64, 59, 18, 0, 36, 3, 8, 15, 42, 9, 0,
    42, 47, 52, 32, 26, 48, 55, 6, 29, 84, 2, 4, 18, 56, 7, 29, 93, 44, 71,
    3, 86, 66, 31, 65, 0, 79, 20, 65, 52, 13])

capacity = 850

def greedy_knapsack_weight(weights, values, capacity):
    """Consider lighter items first; return a feasible binary solution."""
    items = sorted(zip(weights, values, range(len(weights))))
    solution = np.zeros(len(weights), dtype=int)
    total_value, total_weight = 0, 0
    for weight, value, index in items:
        if total_weight + weight <= capacity:
            solution[index] = 1
            total_weight += weight
            total_value += value
    return solution, total_value, total_weight


def greedy_knapsack_value(weights, values, capacity):
    """Consider more valuable items first, skipping those that do not fit."""
    items = sorted(zip(values, weights, range(len(weights))), reverse=True)
    solution = np.zeros(len(weights), dtype=int)
    total_value, total_weight = 0, 0
    for value, weight, index in items:
        if total_weight + weight <= capacity:
            solution[index] = 1
            total_weight += weight
            total_value += value
    return solution, total_value, total_weight


def greedy_knapsack_ratio(weights, values, capacity):
    """Consider value/weight ratios, taking positive-value free items first."""
    ratios = np.divide(values, weights, out=np.full(len(weights), np.inf),
                       where=weights != 0)
    items = sorted(zip(ratios, values, weights, range(len(weights))), reverse=True)
    solution = np.zeros(len(weights), dtype=int)
    total_value, total_weight = 0, 0
    for ratio, value, weight, index in items:
        if total_weight + weight <= capacity:
            solution[index] = 1
            total_weight += weight
            total_value += value
    return solution, total_value, total_weight


def initialize_population(pop_size, num_items, rng):
    """Generate random binary candidates; feasibility is assessed separately."""
    return rng.integers(2, size=(pop_size, num_items))


def evaluate_fitness(population, weights, values, capacity, penalty_factor=10):
    """Score candidates for selection; a finite penalty does not enforce capacity."""
    total_weights = population @ weights
    total_values = population @ values
    penalties = penalty_factor * np.maximum(0, total_weights - capacity)
    return total_values - penalties


def roulette_selection(population, fitness, rng):
    """Sample parents with replacement, proportional to shifted fitness."""
    adjusted_fitness = fitness - np.min(fitness) + 1e-6
    probabilities = adjusted_fitness / np.sum(adjusted_fitness)
    selected_indices = rng.choice(len(population), size=len(population),
                                  replace=True, p=probabilities)
    return population[selected_indices]


def tournament_selection(population, fitness, tournament_size, rng):
    """Select one winner per tournament; larger scores are better here."""
    selected_indices = []
    for _ in range(len(population)):
        participants = rng.choice(len(population), tournament_size, replace=False)
        winner = participants[np.argmax(fitness[participants])]
        selected_indices.append(winner)
    return population[selected_indices]


def single_point_crossover(parents, crossover_rate, rng):
    """Recombine binary parents, returning the same number of offspring."""
    num_parents, num_genes = parents.shape
    parents = parents[rng.permutation(num_parents)]
    offspring = []
    for i in range(0, num_parents, 2):
        parent1 = parents[i]
        parent2 = parents[(i + 1) % num_parents]
        child1, child2 = parent1.copy(), parent2.copy()
        if num_genes > 1 and rng.random() < crossover_rate:
            point = rng.integers(1, num_genes)
            child1[:point], child2[:point] = parent2[:point], parent1[:point]
        offspring.extend((child1, child2))
    return np.array(offspring[:num_parents])


def uniform_crossover(parents, crossover_rate, rng):
    """Choose independently which parent supplies each binary gene."""
    num_parents, num_genes = parents.shape
    parents = parents[rng.permutation(num_parents)]
    offspring = []
    for i in range(0, num_parents, 2):
        parent1 = parents[i]
        parent2 = parents[(i + 1) % num_parents]
        child1, child2 = parent1.copy(), parent2.copy()
        if rng.random() < crossover_rate:
            mask = rng.integers(2, size=num_genes).astype(bool)
            child1[mask], child2[mask] = parent2[mask], parent1[mask]
        offspring.extend((child1, child2))
    return np.array(offspring[:num_parents])


def mutation(offspring, mutation_rate, rng):
    """Flip each bit independently with the specified per-gene probability."""
    mutation_matrix = rng.random(offspring.shape) < mutation_rate
    offspring[mutation_matrix] = 1 - offspring[mutation_matrix]
    return offspring


def elitism(population, fitness, elite_size):
    """Copy the highest-scoring individuals into the next population."""
    if elite_size == 0:
        return population[:0].copy()
    elite_indices = np.argsort(fitness)[-elite_size:]
    return population[elite_indices].copy()


def genetic_algorithm(weights, values, capacity, *, rng, pop_size=100,
                      num_generations=100, crossover_rate=0.8,
                      mutation_rate=0.05, elite_percent=0.02,
                      selection_type='roulette', tournament_size=3,
                      crossover_type='single_point', penalty_factor=10):
    """Run one binary GA and return its best feasible solution and fitness traces.

    Histories contain generations 0 through num_generations. The population
    budget is pop_size * (num_generations + 1) fitness evaluations. All item
    values and weights are nonnegative; the empty knapsack is feasible.
    """
    population = initialize_population(pop_size, len(weights), rng)
    elite_size = int(pop_size * elite_percent)
    best_solution = np.zeros(len(weights), dtype=int)
    best_value, best_weight = 0, 0
    average_fitness_history, best_fitness_history = [], []

    for generation in range(num_generations + 1):
        fitness = evaluate_fitness(population, weights, values, capacity,
                                   penalty_factor)
        average_fitness_history.append(float(np.mean(fitness)))
        best_fitness_history.append(float(np.max(fitness)))

        # Selection scores may favor overweight candidates. Keep a feasible
        # incumbent by actual value, independently of the selection policy.
        total_weights = population @ weights
        total_values = population @ values
        feasible_indices = np.flatnonzero(total_weights <= capacity)
        if len(feasible_indices) > 0:
            index = feasible_indices[np.argmax(total_values[feasible_indices])]
            if total_values[index] > best_value:
                best_solution = population[index].copy()
                best_value = total_values[index]
                best_weight = total_weights[index]

        if generation == num_generations:
            break  # The final population has been evaluated and recorded.

        elites = elitism(population, fitness, elite_size)
        if selection_type == 'roulette':
            parents = roulette_selection(population, fitness, rng)
        elif selection_type == 'tournament':
            parents = tournament_selection(population, fitness, tournament_size, rng)
        else:
            raise ValueError("Choose 'roulette' or 'tournament' selection.")

        if crossover_type == 'single_point':
            offspring = single_point_crossover(parents, crossover_rate, rng)
        elif crossover_type == 'uniform':
            offspring = uniform_crossover(parents, crossover_rate, rng)
        else:
            raise ValueError("Choose 'single_point' or 'uniform' crossover.")
        offspring = mutation(offspring, mutation_rate, rng)
        population = np.vstack((elites, offspring[:pop_size - elite_size]))

    return (best_solution, best_value, best_weight,
            average_fitness_history, best_fitness_history)


def plot_fitness_over_generations(avg_fitness_history, best_fitness_history):
    """Show selection scores, including generation 0 and the final population."""
    generations = np.arange(len(avg_fitness_history))
    plt.figure(figsize=(6, 5))
    plt.plot(generations, avg_fitness_history, label='Mean selection fitness')
    plt.plot(generations, best_fitness_history, label='Maximum selection fitness')
    plt.xlabel('Generation')
    plt.ylabel('Penalized fitness')
    plt.title('Selection Fitness over Generations')
    plt.legend()
    plt.tight_layout()
    plt.show()

Representations and Selection

Encoding Schemes

  • Binary encoding: include or exclude each knapsack item.
  • Permutation encoding: order cities in TSP, or assign rows in N-Queens.
  • Value encoding: store integer, real, or categorical parameters directly.

Tournament Selection

Randomly select k distinct individuals, then choose the individual with the largest fitness as a parent. Repeat until enough parents have been selected.

  • Smaller tournaments exert lower selection pressure.
  • Larger tournaments favor high-fitness individuals more strongly.

tournament_selection

def tournament_selection(population, fitness, tournament_size, rng):

    """Select one winner per tournament; larger scores are better here."""

    selected_indices = []
    for _ in range(len(population)):
        participants = rng.choice(len(population), tournament_size, replace=False)
        winner = participants[np.argmax(fitness[participants])]
        selected_indices.append(winner)

    return population[selected_indices]

Discussion

Code
rng = np.random.default_rng(27)
population = initialize_population(100, len(weights), rng)
fitness = evaluate_fitness(population, weights, values, capacity)
plt.figure(figsize=(5, 4))
plt.hist(fitness, bins=10, edgecolor='black')
plt.xlabel('Penalized fitness')
plt.ylabel('Frequency')
plt.title('Fitness in One Random Population')
plt.tight_layout()
plt.show()

for tournament_size in [2, 4, 8, len(population)]:
    participants = rng.choice(len(population), tournament_size, replace=False)
    print(f"Tournament size {tournament_size}: winner fitness {max(fitness[participants])}")

Tournament size 2: winner fitness 4294
Tournament size 4: winner fitness 4939
Tournament size 8: winner fitness 4142
Tournament size 100: winner fitness 5332

Changing Selection

The population, crossover, mutation, and elitism can remain the same:

solution, value, weight, mean_fitness, max_fitness = genetic_algorithm(
    weights, values, capacity, rng=np.random.default_rng(4106),
    selection_type='tournament', tournament_size=3)

Tournament Size: Predict, Then Compare

Will a larger tournament necessarily produce a better feasible knapsack?

Compare the same instance, seed list, operators, and evaluation budget.

Tournament Size: Repeated Runs

Code
comparison_seeds = [4106, 4107, 4108, 4109, 4110]
comparison_budget = 10000
comparison_population = 100
comparison_generations = comparison_budget // comparison_population - 1

tournament_results = {}
for tournament_size in [2, 4, 8]:
    retained_values = []
    for seed in comparison_seeds:
        solution, value, weight, mean_fitness, max_fitness = genetic_algorithm(
            weights, values, capacity, rng=np.random.default_rng(seed),
            pop_size=comparison_population,
            num_generations=comparison_generations,
            selection_type='tournament', tournament_size=tournament_size,
            crossover_type='single_point')
        retained_values.append(value)
    tournament_results[tournament_size] = np.array(retained_values)
    q1, median, q3 = np.percentile(retained_values, [25, 50, 75])
    print(f"k={tournament_size}: median={median:.0f}, IQR={q3-q1:.0f}, best={max(retained_values):.0f}")

plt.figure(figsize=(6, 4))
plt.boxplot(list(tournament_results.values()))
plt.xticks([1, 2, 3], ['k=2', 'k=4', 'k=8'])
plt.xlabel('Tournament size')
plt.ylabel('Best feasible value retained in one run')
plt.title('Tournament Size: Five Paired Seeds')
plt.tight_layout()
plt.show()
print(f"Each run: {comparison_population * (comparison_generations + 1)} fitness evaluations")
k=2: median=7455, IQR=142, best=7475
k=4: median=7492, IQR=26, best=7525
k=8: median=7525, IQR=22, best=7534

Each run: 10000 fitness evaluations

Crossover and Permutations

Crossover

Single-point crossover preserves contiguous segments. This can be useful when neighboring genes form meaningful components.

For knapsack, item order is usually arbitrary. Uniform crossover reduces dependence on that ordering by choosing the source parent independently at each position.

Uniform Crossover

When crossover occurs, a random binary mask determines which positions exchange their source parent.

mask = rng.integers(2, size=num_genes).astype(bool)
child1[mask], child2[mask] = parent2[mask], parent1[mask]

Comparing Crossover Choices

Code
crossover_results = {}
for crossover_type in ['single_point', 'uniform']:
    retained_values = []
    for seed in comparison_seeds:
        solution, value, weight, mean_fitness, max_fitness = genetic_algorithm(
            weights, values, capacity, rng=np.random.default_rng(seed),
            pop_size=comparison_population,
            num_generations=comparison_generations,
            selection_type='tournament', tournament_size=3,
            crossover_type=crossover_type)
        retained_values.append(value)
    crossover_results[crossover_type] = np.array(retained_values)
    q1, median, q3 = np.percentile(retained_values, [25, 50, 75])
    print(f"{crossover_type}: median={median:.0f}, IQR={q3-q1:.0f}, best={max(retained_values):.0f}")

plt.figure(figsize=(6, 4))
plt.boxplot(list(crossover_results.values()))
plt.xticks([1, 2], ['Single point', 'Uniform'])
plt.ylabel('Best feasible value retained in one run')
plt.title('Crossover: Same Budget and Five Paired Seeds')
plt.tight_layout()
plt.show()
single_point: median=7496, IQR=4, best=7526
uniform: median=7491, IQR=35, best=7512

A Tour Is a Permutation

As in Lecture 19, a candidate is a closed tour visiting every city exactly once.

  • Fix city 0 at the start.
  • Recombine the permutation of the remaining cities.
  • Minimize tour cost, while the knapsack example maximizes value.

Would Ordinary Crossover Work?

Consider two parent permutations of the non-anchor cities:

Parent 1:  1 2 | 3 4 5 6 7 8
Parent 2:  4 5 | 2 1 8 7 6 3

What happens if the first child’s prefix comes from Parent 1 and its suffix from Parent 2?

Child:     1 2 | 2 1 8 7 6 3

Order-1 Crossover: Copy a Segment

Apply circular-fill OX1 to the non-anchor cities. Choose two distinct cuts, here positions 2 and 4, and copy the inclusive segment from Parent 1.

Tail position 0 1 2 3 4 5 6 7
Parent 1 1 2 3 4 5 6 7 8
Parent 2 4 5 2 1 8 7 6 3
Child · · 3 4 5 · · ·

Order-1 Crossover: Fill Circularly

Read Parent 2 circularly from position 5:

7 6 3 4 5 2 1 8

Skip cities already copied, leaving 7, 6, 2, 1, 8. Fill the empty child positions 5, 6, 7, 0, 1 in that order.

Tail position 0 1 2 3 4 5 6 7
Child 1 8 3 4 5 7 6 2

Full tour: 0 → 1 → 8 → 3 → 4 → 5 → 7 → 6 → 2 → 0.

Mutation Depends on the Representation

Representation Mutation event Probability applies to
Binary chromosome Flip a bit Each gene
TSP permutation Reverse a segment Each offspring

A rate of 0.20 per offspring does not mean that 20% of its positions are mutated.

Swap and Inversion

  • Swap: exchange two distinct non-anchor positions.
  • Inversion: reverse the inclusive segment between two distinct non-anchor positions.
  • Both preserve the permutation and keep city 0 fixed.

What Must an Operator Preserve?

An operator must produce a candidate with the intended meaning and constraints.

Useful variation should let the search reach different candidates. A finite stochastic run does not enumerate the state space exhaustively.

Budgets and Interpretation

Population Size

A larger population can hold more variation, but evaluating it costs more.

With a fixed evaluation budget, a larger population also permits fewer generations.

Counting Fitness Evaluations

For a population of size P and G completed generations, including the initial population:

B_{\text{used}}=P(G+1).

For a budget B, choose

G=\left\lfloor\frac{B}{P}\right\rfloor-1.

Mutation and Crossover Rates

Higher rates create more opportunities for variation, but may disrupt useful combinations.

Lower rates preserve more existing material, but may limit variation.

Controlled Comparisons

  1. Change one setting relative to a reference configuration.
  2. Use the same instances and seed list; hold the budget fixed unless budget is the factor being studied.
  3. Report typical results and variability, as well as the best result.
  4. Interpret improvement together with population diversity.
  5. Choose settings on a development instance before evaluating transfer.

Independent Restarts

A run may converge to poor candidates. Independent restarts examine other initial populations.

The best of r runs uses r times the budget of one run.

Skepticism toward GA

[I]t is quite unnatural to model applications in terms of genetic operators like mutation and crossover on bit strings. The pseudobiology adds another level of complexity between you and your problem. Second, genetic algorithms take a very long time on nontrivial problems. [\ldots] [T]he analogy with evolution – where significant progress require [sic] millions of years – can be quite appropriate. […]

I have never encountered any problem where genetic algorithms seemed to me the right way to attack it. Further, I have never seen any computational results reported using genetic algorithms that have favorably impressed me. Stick to simulated annealing for your heuristic search voodoo needs.

Greedy: Value-to-Weight Ratio

The two greedy strategies in Lecture 20 ignored either value or weight. A third strategy considers value per unit weight.

ratios = np.divide(values, weights, out=np.full(len(weights), np.inf),
                   where=weights != 0)

greedy_knapsack_ratio

solution, total_value, total_weight = greedy_knapsack_ratio(weights, values, capacity)
print(f"Solution: {solution}")
print(f"Value: {total_value}")
print(f"Weight: {total_weight}")
Solution: [1 1 0 1 1 0 1 0 0 0 1 1 1 0 1 1 1 1 1 1 0 1 1 0 1 0 0 1 1 1 1 1 1 0 1 0 0
 0 1 1 0 1 1 0 1 0 0 1 1 1]
Value: 7534
Weight: 850

Comparing SA and GA

Aspect Simulated annealing Genetic algorithm
Maintained candidates One current candidate and a retained best A population and a retained best
Variation Propose a random neighbor Recombine and mutate candidates
Preference Accept improvements and some worsening moves Favor candidates through selection and elitism
Main controls Temperature, cooling, neighborhood, budget Population, operators, rates, selection, budget
Possible difficulty Trapping or insufficient exploration Loss of diversity and premature convergence
Evaluation Repeated runs against baselines Repeated runs against baselines

Epilogue

Summary

  • Representation determines which variation operators produce valid candidates.
  • Tournament size controls selection pressure; higher pressure is not always better.
  • OX1 and inversion preserve permutations using explicit conventions.
  • Mutation probability must identify its event: a gene or an offspring.
  • Fixed budgets, repeated seeds, and baselines support interpretable comparisons.
  • Conclusions should be limited to the instances and settings investigated.

Next Lecture

Lecture 22: Adversarial Search introduces an opponent who can choose replies. Minimax and alpha–beta pruning address that different decision problem.

References

Bye, Robin T., Magnus Gribbestad, Ramesh Chandra, and Ottar L. Osen. 2021. “A Comparison of GA Crossover and Mutation Methods for the Traveling Salesman Problem.” In Innovations in Computational Intelligence and Computer Vision, edited by Manoj Kumar Sharma, Vijaypal Singh Dhaka, Thinagaran Perumal, Nilanjan Dey, and João Manuel R. S. Tavares. Springer Singapore.
Cattolico, Mike, and Vincent A Cicirello. 2006. “Non-wrapping order crossover: an order preserving crossover operator that respects absolute position.” Proceedings of the 8th Annual Conference on Genetic and Evolutionary Computation, 1125–32. https://doi.org/10.1145/1143997.1144177.
Davis, Lawrence. 2014. “Job Shop Scheduling with Genetic Algorithms.” Proceedings of the First International Conference on Genetic Algorithms and Their Applications, 136–40.
Goldberg, David E, and Robert Lingle. 2014. “Alleles, Loci, and the Traveling Salesman Problem.” Proceedings of the First International Conference on Genetic Algorithms and Their Applications, 154–59.
Kramer, Oliver. 2017. Genetic Algorithm Essentials. Studies in Computational Intelligence ; 679. Springer.
Mitchell, Melanie. 1998. An Introduction to Genetic Algorithms. MIT Press.
Russell, Stuart, and Peter Norvig. 2020. Artificial Intelligence: A Modern Approach. 4th ed. Pearson. http://aima.cs.berkeley.edu/.
Skiena, Steven S. 2008. The Algorithm Design Manual. Springer. https://doi.org/10.1007/978-1-84800-070-4.

Appendix

Other Crossover Variants

k-point crossover chooses several cut positions and alternates the source parent between segments. Like single-point crossover, it is appropriate only when the resulting chromosome remains meaningful.

Partially Mapped Crossover (PMX)

Other Mutation Operators

  • Binary: flip each selected bit. A per-gene rate of 1/n gives one expected flip.
  • Integer or categorical values: replace a selected gene with another permitted value.
  • Real values: sample a replacement within its allowed interval, or use a suitable perturbation.
  • Permutations: use swaps, inversions, or other moves that preserve the permutation.

Comprehensive Example: Knapsack

The knapsack companion notebook provides a reproducible comparison and an appendix for running the original collection of 25 additional instances.

Comprehensive Example: External Study

Fredj Kharroubi’s knapsack study compares generate-and-test, greedy search, simulated annealing, and a genetic algorithm.

Frameworks

  • DEAP: evolutionary computation for prototyping and experimentation.
  • PyGAD: Python tools for genetic algorithms.

Genetic Programming

Genetic programming searches over a population of candidate programs, evaluated by a fitness function.

It extends the population-search idea beyond the fixed-length vectors used in the main examples.

Genetic Programming: Crossover

Genetic Programming: Demonstration

Machine Learning Control: Genetic Programming.

Further Readings

Resources

Marcel Turcotte

[email protected]

School of Electrical Engineering and Computer Science (EECS)

University of Ottawa