Evolutionary Machine Learning in Python
This program demonstrates a simple implementation of evolutionary machine learning using a genetic algorithm to optimize the weights of a neural network. The neural network is trained to perform a simple classification task.
Required Libraries
numpy for numerical computations
torch for neural networks
torch.nn for neural network modules
torch.optim for optimization algorithms
random for random number generation
Code
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import random
# Set the seed for reproducibility
torch.manual_seed(0)
random.seed(0)
np.random.seed(0)
# Define the neural network model
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(2, 10) # input layer (2) -> hidden layer (10)
self.fc2 = nn.Linear(10, 2) # hidden layer (10) -> output layer (2)
def forward(self, x):
x = torch.relu(self.fc1(x)) # activation function for hidden layer
x = self.fc2(x)
return x
# Define the fitness function
def fitness(model, inputs, labels):
# Evaluate the model on the given inputs and labels
outputs = model(torch.tensor(inputs, dtype=torch.float32))
_, predicted = torch.max(outputs, 1)
accuracy = (predicted == torch.tensor(labels)).sum().item() / len(labels)
return accuracy
# Define the genetic algorithm
class GeneticAlgorithm:
def __init__(self, population_size, mutation_rate, inputs, labels):
self.population_size = population_size
self.mutation_rate = mutation_rate
self.inputs = inputs
self.labels = labels
self.population = [Net() for _ in range(population_size)]
def selection(self):
# Evaluate the fitness of each model in the population
fitnesses = [fitness(model, self.inputs, self.labels) for model in self.population]
# Select the fittest models
selected_indices = np.argsort(fitnesses)[-int(self.population_size/2):]
selected_models = [self.population[i] for i in selected_indices]
return selected_models
def crossover(self, parent1, parent2):
# Perform crossover between two parent models
child = Net()
child.fc1.weight.data = (parent1.fc1.weight.data + parent2.fc1.weight.data) / 2
child.fc1.bias.data = (parent1.fc1.bias.data + parent2.fc1.bias.data) / 2
child.fc2.weight.data = (parent1.fc2.weight.data + parent2.fc2.weight.data) / 2
child.fc2.bias.data = (parent1.fc2.bias.data + parent2.fc2.bias.data) / 2
return child
def mutation(self, model):
# Perform mutation on a model
if random.random() < self.mutation_rate:
model.fc1.weight.data += torch.randn_like(model.fc1.weight.data) * 0.1
model.fc1.bias.data += torch.randn_like(model.fc1.bias.data) * 0.1
model.fc2.weight.data += torch.randn_like(model.fc2.weight.data) * 0.1
model.fc2.bias.data += torch.randn_like(model.fc2.bias.data) * 0.1
def next_generation(self):
# Select the fittest models
selected_models = self.selection()
# Create a new generation
new_generation = []
while len(new_generation) < self.population_size:
parent1, parent2 = random.sample(selected_models, 2)
child = self.crossover(parent1, parent2)
self.mutation(child)
new_generation.append(child)
self.population = new_generation
# Example usage
if __name__ == "__main__":
# Generate some random data for classification
inputs = np.random.rand(100, 2)
labels = (inputs[:, 0] > inputs[:, 1]).astype(int)
# Create a genetic algorithm instance
ga = GeneticAlgorithm(population_size=100, mutation_rate=0.1, inputs=inputs, labels=labels)
# Evolve the population over 100 generations
for generation in range(100):
ga.next_generation()
# Evaluate the fitness of the best model in the current generation
best_model = max(ga.population, key=lambda model: fitness(model, inputs, labels))
print(f"Generation {generation+1}, Best Fitness: {fitness(best_model, inputs, labels)}")
# Evaluate the best model in the final generation
best_model = max(ga.population, key=lambda model: fitness(model, inputs, labels))
print(f"Final Best Fitness: {fitness(best_model, inputs, labels)}")
How it Works
- The program defines a simple neural network model using PyTorch.
- The
fitness function evaluates the performance of a model on a given classification task.
- The
GeneticAlgorithm class implements a genetic algorithm to optimize the weights of the neural network.
- The
selection method selects the fittest models in the current generation based on their fitness.
- The
crossover method performs crossover between two parent models to create a child model.
- The
mutation method applies random mutations to a model.
- The
next_generation method creates a new generation of models by selecting the fittest models, performing crossover, and applying mutations.
- In the example usage, we create a genetic algorithm instance and evolve the population over 100 generations.
- We evaluate the fitness of the best model in each generation and print the results.
Advantages and Limitations
- Advantages:
- The genetic algorithm can be used to optimize the weights of a neural network without requiring gradient information.
- The algorithm is robust to local minima and can explore a large search space.
- Limitations:
- The genetic algorithm can be computationally expensive and may require a large number of generations to converge.
- The algorithm may not be suitable for large-scale neural networks or complex tasks.
Future Work
- Improve the genetic algorithm by using more advanced techniques, such as adaptive mutation rates or more sophisticated crossover methods.
- Apply the genetic algorithm to more complex tasks, such as image classification or natural language processing.
- Compare the performance of the genetic algorithm with other optimization methods, such as gradient-based optimization or Bayesian optimization.