Update genetic_algorithm_optimization.py

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

View File

@ -1,6 +1,7 @@
import random import random
from collections.abc import Callable, Sequence from collections.abc import Callable, Sequence
from concurrent.futures import ThreadPoolExecutor from concurrent.futures import ThreadPoolExecutor
import numpy as np import numpy as np
# Parameters # Parameters
@ -82,10 +83,10 @@ class GeneticAlgorithm:
... ) ... )
>>> individual = np.array([1.0, 2.0]) >>> individual = np.array([1.0, 2.0])
>>> ga.fitness(individual) >>> ga.fitness(individual)
5.0 # The fitness should be 1^2 + 2^2 = 5 -5.0 # The fitness should be -1^2 + 2^2 = 5 for minimizing
>>> ga.maximize = True >>> ga.maximize = True
>>> ga.fitness(individual) >>> ga.fitness(individual)
-5.0 # The fitness should be -5 when maximizing 5.0 # The fitness should be 1^2 + 2^2 = 5 when maximizing
""" """
value = float(self.function(*individual)) # Ensure fitness is a float value = float(self.function(*individual)) # Ensure fitness is a float
return value if self.maximize else -value # If minimizing, invert the fitness return value if self.maximize else -value # If minimizing, invert the fitness
@ -114,9 +115,11 @@ class GeneticAlgorithm:
>>> selected_parents = ga.select_parents(population_score) >>> selected_parents = ga.select_parents(population_score)
>>> len(selected_parents) >>> len(selected_parents)
2 # Should select the two parents with the best fitness scores. 2 # Should select the two parents with the best fitness scores.
>>> np.array_equal(selected_parents[0], np.array([1.0, 2.0])) # Parent 1 should be [1.0, 2.0] >>> np.array_equal(selected_parents[0], np.array([1.0, 2.0]))
# Parent 1 should be [1.0, 2.0]
True True
>>> np.array_equal(selected_parents[1], np.array([-1.0, -2.0])) # Parent 2 should be [-1.0, -2.0] >>> np.array_equal(selected_parents[1], np.array([-1.0, -2.0]))
# Parent 2 should be [-1.0, -2.0]
True True
""" """
population_score.sort(key=lambda score_tuple: score_tuple[1], reverse=True) population_score.sort(key=lambda score_tuple: score_tuple[1], reverse=True)
@ -237,6 +240,7 @@ class GeneticAlgorithm:
>>> isinstance(best_solution[1], float) # Second element should be a float >>> isinstance(best_solution[1], float) # Second element should be a float
True True
""" """
best_individual = None
for generation in range(self.generations): for generation in range(self.generations):
# Evaluate population fitness (multithreaded) # Evaluate population fitness (multithreaded)
population_score = self.evaluate_population() population_score = self.evaluate_population()