Population-Based Metaheuristics

CSI 4106 Introduction to Artificial Intelligence

Marcel Turcotte

Version: Nov 22, 2026 14:49

Preamble

Message of the Day (1/2)

Message of the Day (2/2)

Learning Objectives

  • Explain how population-based search differs from the single-trajectory methods of Lecture 19.
  • Identify the roles of representation, fitness, selection, crossover, mutation, and elitism.
  • Construct a binary genetic algorithm for the 0/1 knapsack problem.
  • Distinguish selection fitness from feasibility and the value of the best feasible solution.
  • Interpret one seeded run and its population-fitness trace without treating it as a performance guarantee.

Introduction

Metaheuristics

Definition

Metaheuristics are higher-level procedures or heuristics designed to guide the search for solutions in optimization problems with large solution spaces, aiming to find good solutions more efficiently than traditional methods.

Metaheuristics balance exploitation and exploration to help escape local optima, often incorporating randomness, memory, or adaptive mechanisms.

Definition

A genetic algorithm is an evolutionary optimization technique that uses a population of candidate solutions, evolving them through selection, crossover, and mutation to search for high-quality solutions. A finite run need not find a global optimum.

Applications

  • Optimization: Solving complex engineering, logistics, and scheduling problems.
  • Machine Learning: Feature selection, hyperparameter tuning, and evolving neural network architectures.
  • Robotics: Path planning, sensor optimization, control strategy development, and robot designs1.

From Biology to Genetic Algorithms

There is probably no more original, more complex, and bolder concept in the history of ideas than Darwin’s mechanistic explanation of adaptation.

If I were to give an award for the single best idea anyone has ever had, I’d give it to Darwin, ahead of Newton & Einstein and everyone else.

Definition

Natural selection is a non-random difference in reproductive output among replicating entities, often due indirectly to differences in survival in a particular environment, leading to an increase in the proportion of beneficial, heritable characteristics within a population from one generation to the next.

Discussion

  • What are the essential components?
  • What is the structure of the algorithm?

Components

Basic GA

  1. Initialize population
  2. Compute the fitness
  3. Select individuals (chromosomes)
  4. Crossover
  5. Mutation
  6. If not done, goto 2

Choices

  • How to encode a candidate solution or state?
  • How to select candidate solutions?
  • How to define the crossover operator?
  • How to define the mutation operator?
  • How to calculate the fitness?

Problem

0/1 knapsack problem: Given items with defined weights and values, the objective is to maximize total value by selecting items for a knapsack without surpassing a fixed capacity. Each item must be either fully included (1) or excluded (0).

Problem (continued)

\begin{aligned} & \text { maximize } \sum_{i=1}^n x_i \cdot v_i \\ & \text { subject to } \sum_{i=1}^n x_i \cdot w_i \leq W \text { and } x_i \in\{0,1\} . \end{aligned}

where v_i and w_i represent the value and the weight of item i, respectively, W represents the fixed maximum weight, x_i is a binary variable indicating if item i is included (1) or excluded (0), and there are n items.

Applications

  1. Finance and Investment: In a simplified investment-selection model, each investment has a stated cost and an estimated return. The knapsack framework selects investments to maximize return within a fixed budget.

  2. Resource Allocation: Common in project management, where resources (budget, personnel, time) need to be allocated across projects or tasks to maximize overall value, taking into account limited availability.

  3. Supply Chain and Logistics: Used to maximize the value of goods transported within vehicle weight or volume constraints. It can also be applied in warehouse storage, where space is limited, and high-value items are prioritized.

  4. Ad Placement and Marketing: Used in digital advertising to select the most profitable combination of ads to display within limited space (e.g., website or app banner space), maximizing revenue under size or display constraints.

Greedy Algorithms

Greedy algorithms make the decision of what to do next by selecting the best local option from all available choices without regard to the global structure.

Data

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

Executable Python Reference

Code
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()

Ascending order of weight

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

greedy_knapsack_weight

solution, total_value, total_weight = greedy_knapsack_weight(weights, values, capacity)

print(f"Solution: {solution}")
print(f"Value: {total_value}")
print(f"Weight: {total_weight}")
Solution: [1 1 1 1 0 0 1 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 0
 1 0 1 0 0 1 0 1 0 1 0 1 1]
Value: 5891
Weight: 817

Descending value order

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

greedy_knapsack_value

solution, total_value, total_weight = greedy_knapsack_value(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 1 1 1 1 0 1 1 0 1 0 1 1 1 1 0 0 0 0 0 0 1 1 0 0 0 1 0 0
 0 1 1 0 1 1 0 1 0 0 1 1 1]
Value: 7339
Weight: 849

GA Implementation

Overview

Encoding

Population

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))

Data

pop_size_small = 12
num_items_small = 10
values_small = values[:num_items_small]
weights_small = weights[:num_items_small]
capacity_small = 125

Population

rng = np.random.default_rng(4106)
population = initialize_population(pop_size_small, num_items_small, rng)
population
array([[0, 1, 1, 1, 0, 1, 0, 1, 0, 1],
       [1, 1, 0, 1, 1, 1, 0, 1, 1, 0],
       [0, 1, 1, 1, 0, 0, 1, 1, 0, 0],
       [1, 1, 0, 0, 1, 1, 0, 1, 1, 1],
       [1, 1, 1, 0, 1, 1, 1, 0, 0, 0],
       [1, 1, 1, 0, 1, 0, 0, 1, 1, 0],
       [1, 1, 0, 0, 1, 0, 1, 1, 0, 1],
       [0, 0, 1, 0, 1, 0, 0, 0, 0, 0],
       [0, 0, 0, 1, 1, 0, 1, 0, 1, 1],
       [0, 1, 1, 1, 1, 1, 0, 1, 0, 1],
       [1, 1, 0, 0, 0, 0, 0, 0, 0, 0],
       [1, 0, 0, 0, 0, 0, 1, 1, 1, 1]])

Population

The proposed method for initializing the population presents a problem.

Fitness

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

Fitness

fitness = evaluate_fitness(population, weights_small, values_small, capacity_small, penalty_factor = 0.5)
fitness
array([ 433. , 1101.5,  544.5, 1075.5, 1181.5, 1006.5, 1222. ,  490. ,
        948. ,  824. ,  443. ,  806. ])

Roulette Wheel Selection

Roulette wheel selection is a stochastic selection method where the probability of selecting an individual is proportional to a nonnegative selection score. Our implementation uses shifted fitness, since penalties can make raw fitness negative.

roulette_selection

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]

roulette_selection

offspring = roulette_selection(population, fitness, rng)
offspring
array([[1, 1, 1, 0, 1, 1, 1, 0, 0, 0],
       [1, 1, 0, 1, 1, 1, 0, 1, 1, 0],
       [1, 1, 0, 0, 1, 0, 1, 1, 0, 1],
       [1, 1, 1, 0, 1, 1, 1, 0, 0, 0],
       [1, 1, 0, 1, 1, 1, 0, 1, 1, 0],
       [1, 1, 0, 0, 1, 0, 1, 1, 0, 1],
       [1, 1, 0, 0, 1, 0, 1, 1, 0, 1],
       [1, 1, 1, 0, 1, 0, 0, 1, 1, 0],
       [1, 1, 1, 0, 1, 1, 1, 0, 0, 0],
       [1, 1, 0, 0, 1, 0, 1, 1, 0, 1],
       [1, 0, 0, 0, 0, 0, 1, 1, 1, 1],
       [1, 1, 0, 1, 1, 1, 0, 1, 1, 0]])

Crossover

Crossover

Parents

Offspring

Crossover

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])

Mutation

Mutate

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

Elitism

Elitism in genetic algorithms is a strategy where a subset of the fittest individuals from the current generation is directly carried over to the next generation.

The copied individuals preserve high selection fitness within the population. With a penalty-based score, this does not by itself guarantee a feasible answer; the best feasible result is retained separately.

Elitism

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()

Overview

Fitness and Feasibility

Can the highest-scoring chromosome still exceed capacity?

Keep the best feasible solution encountered, independently of the fitness used for selection.

The Complete Search Loop

for generation in range(num_generations + 1):

    fitness = evaluate_fitness(population, weights, values, capacity)
    # Record fitness and retain the best feasible candidate by actual value.

    if generation == num_generations:
        break

    elites = elitism(population, fitness, elite_size)
    parents = roulette_selection(population, fitness, rng)
    offspring = single_point_crossover(parents, crossover_rate, rng)
    offspring = mutation(offspring, mutation_rate, rng)
    population = np.vstack((elites, offspring[:pop_size - elite_size]))

One Seeded Run

rng = np.random.default_rng(13)
solution, total_value, total_weight, avg_fitness_history, best_fitness_history = genetic_algorithm(
    weights, values, capacity, rng=rng)
print(f"Solution: {solution}")
print(f"Feasible value: {total_value}")
print(f"Weight: {total_weight} / capacity {capacity}")
Solution: [1 1 0 0 1 0 1 0 0 0 1 1 1 1 1 1 1 1 0 1 1 1 1 0 0 1 0 1 0 0 1 1 1 0 1 0 0
 1 1 0 0 1 1 0 1 0 0 1 1 1]
Feasible value: 7186
Weight: 847 / capacity 850

Fitness over Generations

Code
plot_fitness_over_generations(avg_fitness_history, best_fitness_history)

An Exact Benchmark

For this particular 50-item instance, the optimal value is 7,534, at weight 850.

What Does One Run Tell Us?

  • It checks that the components work together on this example.
  • It shows one search trajectory and one feasible result.
  • Comparing methods requires repeated runs and an explicit computational budget.

Epilogue

Summary

  • A GA searches with a population of encoded candidates.
  • Selection, crossover, and mutation have different roles; elitism preserves chosen individuals.
  • Fitness guides selection, while feasibility determines whether a knapsack is an acceptable answer.
  • The algorithm retains the best feasible candidate encountered and records generations 0 through the final generation.
  • A seeded example supports understanding and validation; performance conclusions require controlled comparisons.

Next Lecture

Lecture 21 examines representation-dependent operators, selection pressure, and controlled experiments, including the permutation representation used in Assignment 4.

References

Dennett, Daniel C. 1995. “Darwin’s Dangerous Idea.” The Sciences 35 (3): 34–40.
Eddaly, M., B. Jarboui, and P. Siarry. 2023. Metaheuristics for Machine Learning: New Advances and Tools. Computational Intelligence Methods and Applications. Springer Nature Singapore. https://books.google.ca/books?id=yXMtzwEACAAJ.
Gil-Rios, Miguel-Angel, Ivan Cruz-Aceves, Fernando Cervantes-Sanchez, Igor Guryev, and Juan-Manuel López-Hernández. 2021. “Automatic Enhancement of Coronary Arteries Using Convolutional Gray-Level Templates and Path-Based Metaheuristics.” Chap. 8 in Recent Trends in Computational Intelligence Enabled Research, edited by Siddhartha Bhattacharyya, Paramartha Dutta, Debabrata Samanta, Anirban Mukherjee, and Indrajit Pan. Academic Press.
Gregory, T. Ryan. 2009. “Understanding Natural Selection: Essential Concepts and Common Misconceptions.” Evolution: Education and Outreach 2 (2): 156–75. https://doi.org/10.1007/s12052-009-0128-1.
Holland, John H. 1973. “Genetic Algorithms and the Optimal Allocation of Trials.” SIAM Journal on Computing 2 (2): 88–105. https://doi.org/10.1137/0202009.
Holland, John H. 1992. “Genetic Algorithms.” Scientific American 267: 66–73. https://www.jstor.org/stable/10.2307/24939139.
Mayr, Ernst. 1982. The Growth of Biological Thought: Diversity, Evolution, and Inheritance. Harvard University Press.
Mitchell, Melanie. 1998. An Introduction to Genetic Algorithms. MIT Press.
Oliva, D., E. H. Houssein, and S. Hinojosa. 2021. Metaheuristics in Machine Learning: Theory and Applications. Studies in Computational Intelligence. Springer International Publishing. https://books.google.ca/books?id=Zlw4EAAAQBAJ.
Russell, Stuart, and Peter Norvig. 2020. Artificial Intelligence: A Modern Approach. 4th ed. Pearson. http://aima.cs.berkeley.edu/.
Santos Amorim, Elisa Portes dos, Carolina Ribeiro Xavier, Ricardo Silva Campos, and Rodrigo Weber dos Santos. 2012. “Comparison Between Genetic Algorithms and Differential Evolution for Solving the History Matching Problem.” In Computational Science and Its Applications - ICCSA 2012 - 12th International Conference, Salvador de Bahia, Brazil, June 18-21, 2012, Proceedings, Part I, edited by Beniamino Murgante, Osvaldo Gervasi, Sanjay Misra, et al., vol. 7333. Lecture Notes in Computer Science. Springer. https://doi.org/10.1007/978-3-642-31125-3\_48.
Skiena, Steven S. 2008. The Algorithm Design Manual. Springer. https://doi.org/10.1007/978-1-84800-070-4.

Appendix

Bit-Flip Mutation in NumPy

rng = np.random.default_rng(42)

offspring = initialize_population(4, 10, rng)

num_offspring, num_genes = offspring.shape

print("Offspring:")
print(offspring)
Offspring:
[[0 1 1 0 0 1 0 1 0 0]
 [1 1 1 1 1 1 1 0 1 0]
 [1 0 0 1 1 1 0 1 1 0]
 [0 0 0 1 1 0 1 1 0 1]]
mutation_rate = 0.05
mutation_matrix = rng.random((num_offspring, num_genes)) < mutation_rate

print("Mutation matrix:")
print(mutation_matrix)
Mutation matrix:
[[False False False False False False False  True False False]
 [False False False False False False False False False False]
 [False False False False False False False False False False]
 [False  True False False False False False False False False]]
print("offspring[mutation_matrix]:")
print(offspring[mutation_matrix])
offspring[mutation_matrix]:
[1 0]
print("1 - offspring[mutation_matrix]:")
print(1 - offspring[mutation_matrix])
1 - offspring[mutation_matrix]:
[0 1]
offspring[mutation_matrix] = 1 - offspring[mutation_matrix]

print("Mutated offspring:")
print(offspring)
Mutated offspring:
[[0 1 1 0 0 1 0 0 0 0]
 [1 1 1 1 1 1 1 0 1 0]
 [1 0 0 1 1 1 0 1 1 0]
 [0 1 0 1 1 0 1 1 0 1]]

Repeated Runs and Best-of-100

Code
seeds = range(4106, 4206)
run_values = []
best_of_100 = None
for seed in seeds:
    result = genetic_algorithm(weights, values, capacity,
                               rng=np.random.default_rng(seed))
    run_values.append(result[1])
    if best_of_100 is None or result[1] > best_of_100[1]:
        best_of_100 = result

q1, median, q3 = np.percentile(run_values, [25, 50, 75])
print(f"100 independent runs: median feasible value {median:.1f}, IQR {q3 - q1:.1f}")
print(f"Best-of-100 feasible value: {best_of_100[1]}")
print(f"Fitness evaluations: 100 × 100 × (100 + 1) = {100 * 100 * 101:,}")
plt.figure(figsize=(6, 4))
plt.hist(run_values, bins=12, edgecolor='black')
plt.axvline(7534, color='red', linestyle='--', label='Exact optimum')
plt.xlabel('Best feasible value within a run')
plt.ylabel('Number of runs')
plt.title('Distribution across 100 Independent Runs')
plt.legend()
plt.tight_layout()
plt.show()
100 independent runs: median feasible value 7286.5, IQR 113.5
Best-of-100 feasible value: 7433
Fitness evaluations: 100 × 100 × (100 + 1) = 1,010,000

Using Google OR-Tools

The following reference implementation uses the data defined above and requires OR-Tools.

from ortools.algorithms.python import knapsack_solver

def solve_using_ortools(values, weights, capacity):
    solver = knapsack_solver.KnapsackSolver(
        knapsack_solver.SolverType.KNAPSACK_MULTIDIMENSION_BRANCH_AND_BOUND_SOLVER,
        "KnapsackExample")
    solver.init(values.tolist(), [weights.tolist()], [int(capacity)])
    optimal_value = solver.solve()
    packed_items = [i for i in range(len(values))
                    if solver.best_solution_contains(i)]
    total_weight = sum(int(weights[i]) for i in packed_items)
    return packed_items, optimal_value, total_weight

packed_items, optimal_value, exact_weight = solve_using_ortools(values, weights, capacity)
print(f"Optimal value: {optimal_value}")
print(f"Weight: {exact_weight}")
print(f"Packed items: {packed_items}")

Application Resources

Applications (continued)

Oliva et al. (2021)

Springer Link

Eddaly et al. (2023)

Springer Link

Image Generation Prompts

The illustrations in this presentation were generated with the following prompts.

Prompt: “Create a humanoid robot with a vintage-futuristic aesthetic, inspired by the style of Atom: The Beginning. The robot has a smooth helmet-like head with a glossy black visor and two large glowing lenses, a golden-bronze mechanical body with exposed joints and wiring, and red circular accents on the torso. Depict the robot as an intelligent engineer engaged in a genetic algorithm workflow. In front of it, show a floating array of candidate solutions—abstract geometric ‘chromosomes’ or vector-like shapes—forming an initial population. The robot is actively performing selection, combining two candidate structures with glowing lines to represent cross-over, while subtle distortions or sparks on another candidate indicate mutation.

The composition should look like an upper-body portrait: the robot slightly angled, one hand raised as if manipulating holographic data. The background is light and minimal, reminiscent of a manga cover. Emphasize clarity and soft lighting to highlight metallic textures, glowing eyes, and the dynamic visual metaphor of evolutionary optimization.”

The image displayed above was generated based on the following prompt: “Illustrate a cartoon girl scout wearing glasses, dressed in a scout uniform featuring brown shorts and hiking boots. She holds a ledger in one hand and a pencil in the other, with a large backpack secured to her back. In front of her, display a variety of items she might choose to pack into her backpack. These items should include a stack of books, a stuffed toy, a cup, assorted snacks, and a pair of binoculars. The scene should evoke a sense of decision-making and exploration.”

Marcel Turcotte

[email protected]

School of Electrical Engineering and Computer Science (EECS)

University of Ottawa