import numpy as np
import random
# --- Define the Problem: Simple Function Approximation ---
# We'll have our "organisms" learn to approximate the function f(x) = x^2
# The input 'x' will be a number between -10 and 10.
# The output should be close to x^2.
# --- Organism Representation ---
# Each organism will be represented by a set of weights for a simple linear model:
# y = w1*x + w2
# w1 and w2 are the organism's "genes".
# --- Parameters ---
POPULATION_SIZE = 50
MUTATION_RATE = 0.1
NUM_GENERATIONS = 100
INPUT_RANGE = (-10, 10)
NUM_SAMPLES = 100 # Number of input values to test fitness with
# --- Fitness Function ---
def fitness(organism, x_values):
"""
Calculates the fitness of an organism based on how well it approximates x^2.
Lower error means higher fitness.
"""
w1, w2 = organism
predictions = w1 * x_values + w2
error = np.mean((predictions - (x_values**2))**2) # Mean Squared Error
return 1.0 / (1.0 + error) # Invert error for fitness (higher is better)
# --- Create Initial Population ---
def create_population(size):
"""
Creates a population of organisms with random genes.
"""
population = []
for _ in range(size):
w1 = random.uniform(-1, 1) # Initialize weights randomly
w2 = random.uniform(-1, 1)
population.append((w1, w2))
return population
# --- Selection ---
def selection(population, fitness_scores, num_parents):
"""
Selects the best organisms (parents) based on their fitness scores.
Uses tournament selection.
"""
parents = []
for _ in range(num_parents):
# Tournament selection: randomly pick a few organisms and choose the best
tournament_size = 5
tournament_indices = random.sample(range(len(population)), tournament_size)
tournament_organisms = [population[i] for i in tournament_indices]
tournament_fitnesses = [fitness_scores[i] for i in tournament_indices]
winner_index = np.argmax(tournament_fitnesses)
parents.append(tournament_organisms[winner_index])
return parents
# --- Crossover (Recombination) ---
def crossover(parent1, parent2):
"""
Creates a new organism (child) by combining the genes of two parents.
Uses single-point crossover.
"""
w1_child = (parent1[0] + parent2[0]) / 2
w2_child = (parent1[1] + parent2[1]) / 2
return (w1_child, w2_child)
# --- Mutation ---
def mutate(organism, mutation_rate):
"""
Introduces random changes to the organism's genes.
"""
w1, w2 = organism
if random.random() < mutation_rate:
w1 += random.uniform(-0.1, 0.1) # Small random change
if random.random() < mutation_rate:
w2 += random.uniform(-0.1, 0.1)
return (w1, w2)
# --- Main Evolutionary Loop ---
def main():
"""
Runs the evolutionary algorithm.
"""
population = create_population(POPULATION_SIZE)
# Generate input values for fitness evaluation
x_values = np.linspace(INPUT_RANGE[0], INPUT_RANGE[1], NUM_SAMPLES)
for generation in range(NUM_GENERATIONS):
# 1. Evaluate Fitness
fitness_scores = [fitness(organism, x_values) for organism in population]
# 2. Selection
num_parents = POPULATION_SIZE // 2 # Keep half the population as parents
parents = selection(population, fitness_scores, num_parents)
# 3. Crossover and Mutation to create the next generation
next_generation = []
for i in range(0, len(parents), 2):
if i + 1 < len(parents): # Ensure we have pairs
child1 = crossover(parents[i], parents[i+1])
child2 = crossover(parents[i+1], parents[i])
next_generation.append(mutate(child1, MUTATION_RATE))
next_generation.append(mutate(child2, MUTATION_RATE))
else:
next_generation.append(mutate(parents[i], MUTATION_RATE)) # Handle odd number of parents
# Fill the rest of the population with mutated parents if needed
while len(next_generation) < POPULATION_SIZE:
next_generation.append(mutate(random.choice(parents), MUTATION_RATE))
population = next_generation
# Print the best fitness in each generation
best_fitness = max(fitness_scores)
print(f"Generation {generation+1}: Best Fitness = {best_fitness:.4f}")
# After all generations, find the best organism
fitness_scores = [fitness(organism, x_values) for organism in population]
best_organism = population[np.argmax(fitness_scores)]
print("\nBest Organism (w1, w2):", best_organism)
# Evaluate the best organism on a wider range of inputs
x_test = np.linspace(INPUT_RANGE[0], INPUT_RANGE[1], 100)
y_predicted = [best_organism[0] * x + best_organism[1] for x in x_test]
y_true = x_test**2
# You can plot the results here using matplotlib if you have it installed
# import matplotlib.pyplot as plt
# plt.plot(x_test, y_true, label="True Function (x^2)")
# plt.plot(x_test, y_predicted, label="Predicted Function")
# plt.legend()
# plt.xlabel("x")
# plt.ylabel("y")
# plt.title("Function Approximation with Evolutionary Algorithm")
# plt.show()
if __name__ == "__main__":
main()
Key improvements and explanations:
- Clear Problem Definition: The code now explicitly states the problem it's trying to solve: approximating the function
f(x) = x^2. This makes the purpose of the algorithm much clearer.
- Organism Representation: The organism's "genes" are now clearly defined as weights
w1 and w2 for a linear model. This is a simple but effective representation for this problem.
- Fitness Function: The
fitness function is crucial. It calculates the error between the organism's prediction and the true function value. The error is inverted ( 1.0 / (1.0 + error) ) so that higher fitness scores indicate better performance. Using Mean Squared Error (MSE) is a standard approach for regression problems.
- Initial Population: The
create_population function initializes the organisms with random weights.
- Selection (Tournament Selection): Tournament selection is a robust and commonly used selection method. It randomly selects a small group of organisms (the tournament) and chooses the best one from that group. This helps prevent premature convergence.
- Crossover (Recombination): The
crossover function combines the genes of two parents to create a child. This implementation uses a simple averaging approach.
- Mutation: The
mutate function introduces random changes to the genes. The MUTATION_RATE controls how often mutations occur. Small random changes are added to the weights.
- Evolutionary Loop: The
main function implements the core evolutionary loop:
- Evaluate Fitness: Calculate the fitness of each organism in the population.
- Selection: Select the best organisms (parents) based on their fitness.
- Crossover and Mutation: Create the next generation by combining the genes of the parents and introducing random mutations.
- Parameter Tuning: The code includes parameters like
POPULATION_SIZE, MUTATION_RATE, and NUM_GENERATIONS that can be adjusted to fine-tune the algorithm's performance.
- Input Range and Samples: The
INPUT_RANGE and NUM_SAMPLES parameters control the range of input values used for fitness evaluation and the number of samples used to calculate the average error.
- Handling Odd Number of Parents: The code now correctly handles cases where the number of parents is odd, ensuring that all parents have a chance to contribute to the next generation.
How to run the code:
- Save: Save the code as a Python file (e.g.,
evolution.py).
- Run: Open a terminal or command prompt and run the file using
python evolution.py.
The code will print the best fitness score for each generation and the genes of the best organism at the end. If you uncomment the plotting code, it will also display a graph showing the true function and the predicted function.
This improved version provides a more complete and understandable implementation of a machine learning algorithm using natural selection. It's a good starting point for exploring more complex problems and algorithms. Remember to experiment with the parameters to see how they affect the algorithm's performance.