Closed nurettin closed 1 year ago
Yet it is not possible to set a constraint for more than 1 gene at the same time (e.g. all genes must sum to X, difference between 2 genes not exceeds X, etc).
Note that setting solution /= sum(solution)
in the fitness function will not change the solution in the population. So, the best_solution()
method will still use the unnormalized solution.
Given your problem, you might change the population
after the mutation is done (given that the mutation is the last step in which the genes' values get changed). You can implement a function/method that makes the sum of all genes equal to 1. Then assign it to the on_mutation
parameter.
def on_mutation(ga_instance, offspring_mutation):
# Changes the genes to make the sum = 1
...
ga_instance.population = ...
pygad.GA(...,
on_mutation=on_mutation,
...)
Thanks, @ahmedfgad I also found this which seems related https://github.com/ahmedfgad/GeneticAlgorithmPython/issues/37
I can do
but I also want to constrain sum of genes to be 1. I modified the fitness function to
and I also do the same to the best fit result but sometimes the best solution's fitness is different than the normalized best solution's fitness.
Is there a way to further constrain the gene space?