Update genetic_algorithm_optimization.py

This commit is contained in:
UTSAV SINGHAL 2024-11-15 14:56:23 +05:30 committed by GitHub
parent dbd29aed76
commit 84b29c0eed
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -60,10 +60,7 @@ class GeneticAlgorithm:
True
"""
return [
rng.uniform(
low=[self.bounds[j][0] for j in range(self.dim)],
high=[self.bounds[j][1] for j in range(self.dim)],
)
np.array([rng.uniform(b[0], b[1]) for b in self.bounds])
for _ in range(self.population_size)
]
@ -122,6 +119,10 @@ class GeneticAlgorithm:
# Parent 2 should be [-1.0, -2.0]
True
"""
if not population_score:
raise ValueError("Population score is empty, cannot select parents.")
population_score.sort(key=lambda score_tuple: score_tuple[1], reverse=True)
selected_count = min(N_SELECTED, len(population_score))
return [ind for ind, _ in population_score[:selected_count]]
@ -244,30 +245,32 @@ class GeneticAlgorithm:
for generation in range(self.generations):
# Evaluate population fitness (multithreaded)
population_score = self.evaluate_population()
# Ensure population_score isn't empty
if not population_score:
raise ValueError("Population score is empty. No individuals evaluated.")
# Check the best individual
best_individual = max(
population_score, key=lambda score_tuple: score_tuple[1]
)[0]
best_individual = max(population_score, key=lambda score_tuple: score_tuple[1])[0]
best_fitness = self.fitness(best_individual)
# Select parents for next generation
parents = self.select_parents(population_score)
next_generation = []
# Generate offspring using crossover and mutation
for i in range(0, len(parents), 2):
parent1, parent2 = parents[i], parents[(i + 1) % len(parents)]
parent1, parent2 = parents[i], parents[(i + 1) % len(parents)] # Wrap around for odd cases
child1, child2 = self.crossover(parent1, parent2)
next_generation.append(self.mutate(child1))
next_generation.append(self.mutate(child2))
# Ensure population size remains the same
self.population = next_generation[: self.population_size]
if verbose and generation % 10 == 0:
print(f"Generation {generation}: Best Fitness = {best_fitness}")
return best_individual