Skip to content

Commit dbd29ae

Browse files
authored
Update genetic_algorithm_optimization.py
1 parent d62f39f commit dbd29ae

File tree

1 file changed

+8
-4
lines changed

1 file changed

+8
-4
lines changed

genetic_algorithm/genetic_algorithm_optimization.py

+8-4
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import random
22
from collections.abc import Callable, Sequence
33
from concurrent.futures import ThreadPoolExecutor
4+
45
import numpy as np
56

67
# Parameters
@@ -82,10 +83,10 @@ def fitness(self, individual: np.ndarray) -> float:
8283
... )
8384
>>> individual = np.array([1.0, 2.0])
8485
>>> ga.fitness(individual)
85-
5.0 # The fitness should be 1^2 + 2^2 = 5
86+
-5.0 # The fitness should be -1^2 + 2^2 = 5 for minimizing
8687
>>> ga.maximize = True
8788
>>> ga.fitness(individual)
88-
-5.0 # The fitness should be -5 when maximizing
89+
5.0 # The fitness should be 1^2 + 2^2 = 5 when maximizing
8990
"""
9091
value = float(self.function(*individual)) # Ensure fitness is a float
9192
return value if self.maximize else -value # If minimizing, invert the fitness
@@ -114,9 +115,11 @@ def select_parents(
114115
>>> selected_parents = ga.select_parents(population_score)
115116
>>> len(selected_parents)
116117
2 # Should select the two parents with the best fitness scores.
117-
>>> np.array_equal(selected_parents[0], np.array([1.0, 2.0])) # Parent 1 should be [1.0, 2.0]
118+
>>> np.array_equal(selected_parents[0], np.array([1.0, 2.0]))
119+
# Parent 1 should be [1.0, 2.0]
118120
True
119-
>>> np.array_equal(selected_parents[1], np.array([-1.0, -2.0])) # Parent 2 should be [-1.0, -2.0]
121+
>>> np.array_equal(selected_parents[1], np.array([-1.0, -2.0]))
122+
# Parent 2 should be [-1.0, -2.0]
120123
True
121124
"""
122125
population_score.sort(key=lambda score_tuple: score_tuple[1], reverse=True)
@@ -237,6 +240,7 @@ def evolve(self, verbose: bool = True) -> np.ndarray:
237240
>>> isinstance(best_solution[1], float) # Second element should be a float
238241
True
239242
"""
243+
best_individual = None
240244
for generation in range(self.generations):
241245
# Evaluate population fitness (multithreaded)
242246
population_score = self.evaluate_population()

0 commit comments

Comments
 (0)