o1-preview-2024-09-12· OpenAI
WildChat-4.8M (AI2)
write code for a genetic algo
- User
write code for a genetic algo
- Assistant
write code for a genetic algo
Sure! Below is an example of a simple genetic algorithm implemented in Python. This code demonstrates the basic components of a genetic algorithm: initialization, selection, crossover, mutation, and iteration over generations.
import random
# Genetic Algorithm Parameters
POPULATION_SIZE = 100
GENES = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ! ' # Possible characters in the genes
TARGET = 'Hello World!' # The target string we're trying to evolve
MUTATION_RATE = 0.01
# Individual class representing a candidate solution
class Individual:
def __init__(self, chromosome=None):
if chromosome is None:
self.chromosome = self._create_genome()
else:
self.chromosome = chromosome
self.fitness = self._calculate_fitness()
def _create_genome(self):
"""Creates a random chromosome (string)."""
return ''.join(random.choices(GENES, k=len(TARGET)))
def _calculate_fitness(self):
"""Calculates fitness score by comparing the chromosome to the target."""
fitness = 0
for gene, target_gene in zip(self.chromosome, TARGET):
if gene == target_gene:
fitness += 1
return fitness
def mate(self, partner):
"""Performs crossover and mutation to produce a new child."""
child_chromosome = []
for gp1, gp2 in zip(self.chromosome, partner.chromosome):
prob = random.random()
# 45% chance to inherit gene from parent 1
if prob < 0.45:
child_chromosome.append(gp1)
# 45% chance to inherit gene from parent 2
elif prob < 0.90:
child_chromosome.append(gp2)
# 10% chance for mutation
else:
child_chromosome.append(random.choice(GENES))
return Individual(''.join(child_chromosome))
def genetic_algorithm():
# Initialize population
generation = 1
found = False
population = [Individual() for _ in range(POPULATION_SIZE)]
while not found:
# Sort population based on fitness (higher is better)
population = sorted(population, key=lambda x: x.fitness, reverse=True)
# If the best individual's fitness is equal to target length, we've found the solution
if population[0].fitness == len(TARGET):
found = True
break
# Print the best individual from current generation
print(f'Generation: {generation}\tString: {population[0].chromosome}\tFitness: {population[0].fitness}')
# New generation
new_generation = []
# Elitism: carry forward the top 10% individuals
s = int((10*POPULATION_SIZE)/100)
new_generation.extend(population[:s])
# From the remaining 90%, create offspring pairs
s = int((90*POPULATION_SIZE)/100)
for _ in range(s):
parent1 = random.choice(population[:50]) # Select from top 50 individuals
parent2 = random.choice(population[:50])
child = parent1.mate(parent2)
new_generation.append(child)
population = new_generation
generation += 1
# Print final result
print(f'Generation: {generation}\tString: {population[0].chromosome}\tFitness: {population[0].fitness}')
print('Finished!')
if __name__ == '__main__':
genetic_algorithm()
Explanation:
_create_genome: Generates a random string of genes._calculate_fitness: Compares the chromosome to the target string and calculates a fitness score.mate: Combines genes from two parents and introduces mutations to create a new individual.Algorithm Steps:
How to Run the Code:
genetic_algorithm.py.python genetic_algorithm.py
Adjusting Parameters:
POPULATION_SIZE: Adjust the number of individuals in the population. Larger sizes may slow down execution but can improve the search.MUTATION_RATE: Change the mutation rate to control genetic diversity. Higher rates may prevent convergence.TARGET: Modify the target string to evolve different phrases.Example Output:
Generation: 1 String: UDHvGAlmYheF Fitness: 1
Generation: 2 String: HelXoWpslDEF Fitness: 6
Generation: 3 String: HellnoWorld! Fitness: 11
Generation: 4 String: Hello World! Fitness: 12
Finished!
Tips for Customization:
_calculate_fitness method to suit other optimization problems.References:
Feel free to ask if you need help customizing the genetic algorithm for a specific application or if you have any questions about how it works!
Not yet included in a published release.