Skip to content

Commit 19e0461

Browse files
[pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
1 parent 7e97562 commit 19e0461

File tree

1 file changed

+37
-18
lines changed

1 file changed

+37
-18
lines changed

genetic_algorithm/genetic_algorithm_optimization.py

+37-18
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,26 @@
22
import numpy as np
33

44
# Parameters
5-
N_POPULATION = 100 # Population size
5+
N_POPULATION = 100 # Population size
66
N_GENERATIONS = 500 # Maximum number of generations
7-
N_SELECTED = 50 # Number of parents selected for the next generation
7+
N_SELECTED = 50 # Number of parents selected for the next generation
88
MUTATION_PROBABILITY = 0.1 # Mutation probability
99
CROSSOVER_RATE = 0.8 # Probability of crossover
1010
SEARCH_SPACE = (-10, 10) # Search space for the variables
1111

12+
1213
# Genetic Algorithm for Function Optimization
1314
class GeneticAlgorithm:
14-
def __init__(self, function, bounds, population_size, generations, mutation_prob, crossover_rate, maximize=True):
15+
def __init__(
16+
self,
17+
function,
18+
bounds,
19+
population_size,
20+
generations,
21+
mutation_prob,
22+
crossover_rate,
23+
maximize=True,
24+
):
1525
self.function = function # Target function to optimize
1626
self.bounds = bounds # Search space bounds (for each variable)
1727
self.population_size = population_size
@@ -20,27 +30,33 @@ def __init__(self, function, bounds, population_size, generations, mutation_prob
2030
self.crossover_rate = crossover_rate
2131
self.maximize = maximize
2232
self.dim = len(bounds) # Dimensionality of the function (number of variables)
23-
33+
2434
# Initialize population
2535
self.population = self.initialize_population()
26-
36+
2737
def initialize_population(self):
2838
# Generate random initial population within the search space
29-
return [np.random.uniform(low=self.bounds[i][0], high=self.bounds[i][1], size=self.dim)
30-
for i in range(self.population_size)]
31-
39+
return [
40+
np.random.uniform(
41+
low=self.bounds[i][0], high=self.bounds[i][1], size=self.dim
42+
)
43+
for i in range(self.population_size)
44+
]
45+
3246
def fitness(self, individual):
3347
# Calculate the fitness value (function value)
3448
value = self.function(*individual)
3549
return value if self.maximize else -value # If minimizing, invert the fitness
36-
50+
3751
def select_parents(self):
3852
# Rank individuals based on fitness and select top individuals for mating
39-
scores = [(individual, self.fitness(individual)) for individual in self.population]
53+
scores = [
54+
(individual, self.fitness(individual)) for individual in self.population
55+
]
4056
scores.sort(key=lambda x: x[1], reverse=True)
4157
selected = [ind for ind, _ in scores[:N_SELECTED]]
4258
return selected
43-
59+
4460
def crossover(self, parent1, parent2):
4561
# Perform uniform crossover
4662
if random.random() < self.crossover_rate:
@@ -49,14 +65,14 @@ def crossover(self, parent1, parent2):
4965
child2 = np.concatenate((parent2[:cross_point], parent1[cross_point:]))
5066
return child1, child2
5167
return parent1, parent2
52-
68+
5369
def mutate(self, individual):
5470
# Apply mutation to an individual with some probability
5571
for i in range(self.dim):
5672
if random.random() < self.mutation_prob:
5773
individual[i] = np.random.uniform(self.bounds[i][0], self.bounds[i][1])
5874
return individual
59-
75+
6076
def evolve(self):
6177
for generation in range(self.generations):
6278
# Select parents based on fitness
@@ -71,15 +87,17 @@ def evolve(self):
7187
next_generation.append(self.mutate(child2))
7288

7389
# Ensure population size remains the same
74-
self.population = next_generation[:self.population_size]
90+
self.population = next_generation[: self.population_size]
7591

7692
# Track the best solution so far
7793
best_individual = max(self.population, key=self.fitness)
7894
best_fitness = self.fitness(best_individual)
79-
95+
8096
if generation % 10 == 0:
81-
print(f"Generation {generation}: Best Fitness = {best_fitness}, Best Individual = {best_individual}")
82-
97+
print(
98+
f"Generation {generation}: Best Fitness = {best_fitness}, Best Individual = {best_individual}"
99+
)
100+
83101
# Return the best individual found
84102
return max(self.population, key=self.fitness)
85103

@@ -88,6 +106,7 @@ def evolve(self):
88106
def target_function(x, y):
89107
return x**2 + y**2 # Example: simple parabolic surface (minimization)
90108

109+
91110
# Set bounds for the variables (x, y)
92111
bounds = [(-10, 10), (-10, 10)] # Both x and y range from -10 to 10
93112

@@ -99,7 +118,7 @@ def target_function(x, y):
99118
generations=N_GENERATIONS,
100119
mutation_prob=MUTATION_PROBABILITY,
101120
crossover_rate=CROSSOVER_RATE,
102-
maximize=False # Set to False for minimization
121+
maximize=False, # Set to False for minimization
103122
)
104123

105124
# Run the genetic algorithm and find the optimal solution

0 commit comments

Comments
 (0)