ahmedfgad / GeneticAlgorithmPython

Source code of PyGAD, a Python 3 library for building the genetic algorithm and training machine learning algorithms (Keras & PyTorch).
https://pygad.readthedocs.io
BSD 3-Clause "New" or "Revised" License
1.85k stars 462 forks source link

Optimize using sum constraint #214

Closed nurettin closed 1 year ago

nurettin commented 1 year ago

I can do

    gene_space={"low": 0, "high": 1},

but I also want to constrain sum of genes to be 1. I modified the fitness function to

     solution /= sum(solution)

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?

ahmedfgad commented 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,
         ...)
nurettin commented 1 year ago

Thanks, @ahmedfgad I also found this which seems related https://github.com/ahmedfgad/GeneticAlgorithmPython/issues/37