Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 7e068dd

Browse files
authored
fix: best_solution for multi-objective optimization
This fix allows to optimize both single-objective and multi-objective optimization cases
1 parent 19d6bb0 commit 7e068dd

File tree

1 file changed

+14
-3
lines changed

1 file changed

+14
-3
lines changed

‎pygad/pygad.py

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2227,8 +2227,19 @@ def best_solution(self, pop_fitness=None):
22272227
raise ValueError(f"The type of the 'pop_fitness' parameter is expected to be list, tuple, or numpy.ndarray but ({type(pop_fitness)}) found.")
22282228

22292229
# Return the index of the best solution that has the best fitness value.
2230-
best_match_idx = numpy.where(
2231-
pop_fitness == numpy.max(pop_fitness))[0][0]
2230+
# For multi-objective optimization: find the index of the solution with the maximum fitness in the first objective,
2231+
# break ties using the second objective, then third, etc.
2232+
pop_fitness_arr = numpy.array(pop_fitness)
2233+
# Get the indices that would sort by all objectives in descending order
2234+
sorted_indices = numpy.lexsort([ -pop_fitness_arr[:,i] for i in reversed(range(pop_fitness_arr.shape[1])) ])
2235+
best_match_idx = sorted_indices[0]
2236+
maximum_fitness_value = pop_fitness_arr[best_match_idx]
2237+
2238+
best_match_list = numpy.where(
2239+
pop_fitness == maximum_fitness_value)
2240+
2241+
best_match_idx = best_match_list[0][0] # Get the first index of the best match.
2242+
22322243

22332244
best_solution = self.population[best_match_idx, :].copy()
22342245
best_solution_fitness = pop_fitness[best_match_idx]
@@ -2494,4 +2505,4 @@ def load(filename):
24942505
except:
24952506
# raise BaseException("Error loading the file. If the file already exists, please reload all the functions previously used (e.g. fitness function).")
24962507
raise BaseException("Error loading the file.")
2497-
return ga_in
2508+
return ga_in

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /