-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenetic_algorithm.py
67 lines (53 loc) · 2.38 KB
/
genetic_algorithm.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# -*- coding: utf-8 -*-
"""genetic_algorithm.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1gRTzndHDYAqsfTOmDmadcYMLtPZRJnYH
"""
#GENETIC ALGORITHM
import random
# Genetic Algorithm parameters
target = "1101010100110010" # The target binary string we want to evolve towards
population_size = 50
mutation_rate = 0.1
generations = 100
# Create an initial population of random binary strings
def create_initial_population(size):
return [''.join(random.choice('01') for _ in range(len(target))) for _ in range(size)]
# Evaluate the fitness of each individual in the population
def calculate_fitness(individual):
return sum(1 for a, b in zip(individual, target) if a == b)
# Select parents for the next generation using roulette wheel selection
def select_parents(population):
total_fitness = sum(calculate_fitness(individual) for individual in population)
probabilities = [calculate_fitness(individual) / total_fitness for individual in population]
return random.choices(population, probabilities, k=2)
# Perform single-point crossover between parents to produce children
def crossover(parent1, parent2):
crossover_point = random.randint(1, len(target) - 1)
child1 = parent1[:crossover_point] + parent2[crossover_point:]
child2 = parent2[:crossover_point] + parent1[crossover_point:]
return child1, child2
# Perform mutation on an individual with a certain probability
def mutate(individual):
mutated = ''.join(
c if random.random() > mutation_rate else random.choice('01')
for c in individual
)
return mutated
# Main genetic algorithm loop
def genetic_algorithm():
population = create_initial_population(population_size)
for generation in range(generations):
population = sorted(population, key=calculate_fitness, reverse=True)
print(f"Generation {generation}: Best fitness = {calculate_fitness(population[0])}, Best individual = {population[0]}")
new_population = []
while len(new_population) < population_size:
parent1, parent2 = select_parents(population)
child1, child2 = crossover(parent1, parent2)
child1 = mutate(child1)
child2 = mutate(child2)
new_population.extend([child1, child2])
population = new_population[:population_size]
# Run the genetic algorithm
genetic_algorithm()