The user wants a program implementing Genetic Algorithms (GA) for optimization.
-
Understand the Goal: The objective is to write code that demonstrates the core concepts of a genetic algorithm: selection, crossover, and mutation, applied to an optimization problem.
-
Choose a Problem: GAs are generic. To make the code understandable, I need a specific problem.
-
Option A: String matching. (Easy to visualize, but less "math-y").
-
Option B: Knapsack problem. (Classic combinatorial optimization).
-
Option C: Function maximization/minimization. (Standard, easy to graph mentally).
-
Selection: Let's go with Function Maximization (e.g., finding the maximum of a specific mathematical function). It's simple to implement and clearly shows "optimization." Specifically, let's try to maximize f(x)=x2 or something slightly more complex like f(x)=xsin(10πx)+1 within a specific range. Actually, a simple bit-counting or the "OneMax" problem is the "Hello World" of GAs, but function optimization feels more like a real use case. Let's do maximizing f(x)=−(x−10)2 (finding the peak at x=10) or a simple equation. Let's stick to the "Knapsack Problem" or "Traveling Salesman" if I want to be fancy, but a simple function maximization is best for a clear, single-file example. Let's try to maximize f(x)=x2 in the range [0,31] using binary encoding. This is the classic introductory example.
-
Refinement: Let's make it slightly more general but still Pythonic. I will implement a continuous function optimizer (e.g., maximizing f(x)=xsin(10πx)+1.0) or a simpler one like finding x where x is max.
-
Decision: I will provide a general framework in Python. I'll use the classic "maximize f(x)=x2" example first (encoded in binary) because it's intuitive, but I will structure the code so the fitness function and individual representation are modular.
-
Identify Key Components of GA:
- Genome/Chromosome: Representation of a solution (e.g., a list of 0s and 1s).
- Population: A collection of genomes.
- Fitness Function: Evaluates how good a genome is.
- Selection: Choosing parents (e.g., Roulette Wheel, Tournament). Tournament is easier to implement and robust.
- Crossover (Recombination): Combining parents to make offspring (e.g., One-point crossover).
- Mutation: Random flipping of bits to maintain diversity.
- Termination: When to stop (max generations or convergence).
-
Drafting the Code Structure (Python):
- Imports:
random, math (if needed).
- Parameters:
POPULATION_SIZE, GENOME_LENGTH, MUTATION_RATE, CROSSOVER_RATE, GENERATIONS.
- Class/Functions:
create_individual()
create_population()
fitness_function(genome) -> decode(genome) -> value.
selection(population) -> Tournament selection.
crossover(parent1, parent2) -> Single point.
mutate(individual) -> Bit flip.
-
Refining the Example Problem:
Let's try to find the x that maximizes f(x)=−(x−10)2. The answer is 10.
- Encoding: Let's use a binary string. 10 bits allows numbers up to 1023. We can map that to a range, or just use integers.
- Let's keep it simple: Maximize the sum of 1s in a binary string (OneMax) is the absolute simplest. It removes the decoding step complexity.
- Alternative: Maximize for . This is standard. 5 bits. . .
-
Writing the Code (Mental Draft):
import random
# Config
POP_SIZE = 10
GENOME_LEN = 5
MUT_RATE = 0.1
# ...
def fitness(genome):
x = binary_to_int(genome)
return x**2
# ... standard GA loop ...
-
Adding Explanations: The user needs to understand why the code is written this way. I should explain:
- Initialization: Random start.
- Evaluation: Who is fit?
- Selection: Survival of the fittest (Tournament).
- Crossover: Mixing traits.
- Mutation: Exploration.
-
Polishing the Code:
- Use meaningful variable names.
- Add comments.
- Include a
main block.
- Print progress (Generation, Best Fitness).
-
Self-Correction/Review during drafting:
- Issue: Roulette wheel selection can be tricky with negative fitness values (though not an issue with x2). Tournament selection is more stable.
- Issue: Elitism. Should I keep the best individual? Yes, usually helps convergence, but for a basic example, maybe keep it simple. I'll stick to generational replacement but maybe mention elitism.
- Improvement: I will create a class
GeneticAlgorithm to make it cleaner, or just a functional script. A functional script is often easier for beginners to read top-to-bottom.
-
Final Plan:
- Define the problem: Maximize f(x)=x2 where x is an integer represented by a 5-bit binary string. (Max possible is 312).
The Problem
We will try to find the value of x that results in the maximum value for the function:
f(x)=x2
within the range of integers [0,31].
While we know the answer is 31, this demonstrates how the algorithm evolves a random population to find the best solution without knowing the math beforehand.
The Python Code
import random
# --- CONFIGURATION ---
POPULATION_SIZE = 10 # Number of individuals in each generation
GENOME_LENGTH = 5 # Length of the binary string (5 bits covers 0-31)
MUTATION_RATE = 0.1 # Probability of a bit flipping
CROSSOVER_RATE = 0.7 # Probability of parents mating
GENERATIONS = 10 # Max number of generations to run
# --- HELPER FUNCTIONS ---
def decode_genome(genome):
"""
Converts a binary list (genome) into an integer (phenotype).
Example: [1, 0, 1] -> 5
"""
# Join bits into a string, then convert from base 2 to base 10
bit_string = "".join(map(str, genome))
return int(bit_string, 2)
def fitness_function(x):
"""
The function we want to MAXIMIZE.
Objective: f(x) = x^2
"""
return x ** 2
def create_individual():
"""
Creates a single individual with a random binary genome.
"""
return [random.randint(0, 1) for _ in range(GENOME_LENGTH)]
def create_population():
"""
Creates the initial random population.
"""
return [create_individual() for _ in range(POPULATION_SIZE)]
# --- GENETIC OPERATORS ---
def selection(population, fitness_scores):
"""
Tournament Selection:
Selects a few individuals at random and picks the best one.
This ensures 'survival of the fittest' while maintaining some diversity.
"""
# Select 2 random indices
idx1 = random.randint(0, len(population) - 1)
idx2 = random.randint(0, len(population) - 1)
# Compare their fitness scores
if fitness_scores[idx1] > fitness_scores[idx2]:
return population[idx1]
else:
return population[idx2]
def crossover(parent1, parent2):
"""
Single-Point Crossover:
Splits two parents at a random point and swaps their tails
to create two children.
"""
if random.random() < CROSSOVER_RATE:
point = random.randint(1, GENOME_LENGTH - 1)
child1 = parent1[:point] + parent2[point:]
child2 = parent2[:point] + parent1[point:]
return child1, child2
else:
# If no crossover, parents pass directly to next gen
return parent1, parent2
def mutate(genome):
"""
Mutation:
Flips bits with a small probability to maintain genetic diversity.
"""
new_genome = genome.copy()
for i in range(len(new_genome)):
if random.random() < MUTATION_RATE:
# Flip 0 to 1, or 1 to 0
new_genome[i] = 1 if new_genome[i] == 0 else 0
return new_genome
# --- MAIN LOOP ---
def run_genetic_algorithm():
# 1. Initialize Population
population = create_population()
print(f"{'Gen':<5} | {'Best Fit':<10} | {'Best X':<10} | {'Avg Fit':<10}")
print("-" * 45)
for generation in range(GENERATIONS):
# 2. Evaluate Fitness
# Map the fitness function to every individual in the population
decoded_values = [decode_genome(ind) for ind in population]
fitness_scores = [fitness_function(x) for x in decoded_values]
# Stats for logging
best_fitness = max(fitness_scores)
best_index = fitness_scores.index(best_fitness)
best_x = decoded_values[best_index]
avg_fitness = sum(fitness_scores) / len(fitness_scores)
print(f"{generation:<5} | {best_fitness:<10} | {best_x:<10} | {avg_fitness:.2f}")
# 3. Create Next Generation
new_population = []
# We need to create enough children to fill the population size
while len(new_population) < POPULATION_SIZE:
# Selection
parent1 = selection(population, fitness_scores)
parent2 = selection(population, fitness_scores)
# Crossover
child1, child2 = crossover(parent1, parent2)
# Mutation
child1 = mutate(child1)
child2 = mutate(child2)
new_population.extend([child1, child2])
# Truncate if we accidentally added too many (due to odd population sizes)
population = new_population[:POPULATION_SIZE]
print("-" * 45)
print(f"Final Result: x = {best_x}, f(x) = {best_fitness}")
if __name__ == "__main__":
run_genetic_algorithm()
How it works
-
Representation (Genome):
Computers process bits efficiently. We represent the solution x as a list of 1s and 0s (binary). Since x is between 0 and 31, we need 5 bits (25=32 possibilities).
-
Initialization:
We create a random population (e.g., 10 people). Initially, these are just random guesses.
-
Fitness Calculation:
We convert the binary back to an integer () and check the "score" (). Higher scores are better.
Sample Output
When you run this, you will see the "Best X" quickly climb toward 31:
Gen | Best Fit | Best X | Avg Fit
---------------------------------------------
0 | 841 | 29 | 264.40
1 | 900 | 30 | 546.90
2 | 961 | 31 | 784.10
...
---------------------------------------------
Final Result: x = 31, f(x) = 961