Python Forum

Full Version: Genetic Algorithm
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hey everyone, I'm having some problems with my GA code, I'm leaving the github link below. Appreciate any help!!! Thksss!!!

https://github.com/LeoUpperThrower4/GeneticAlgorithm
Most of us are not specialists in genetic algorithms. If you can frame your post as a specific question, rather than "I'm having some problems" then we might be able to help in spite of our general-ness. For example, you say "I don't know what I'm doing wrong" on Github, but I don't even know why you think you're doing something wrong. If you give some more details, we might be able to help :)
I'm not totally sure, but skimming through your code I see two potential problems. One, when you mutate, you appear to come up with an entirely new, random population. Typically when you mutate in a genetic algorithm, you mutate some of the genes in some of the individuals. For example, at crossover (breeding) you might have a 10% that one gene is randomized.

Second, you are biasing toward the worst genes. You take a well performing individual and replace half their genes with those of a poorly performing individual. Then you put that half good/half bad and the totally bad individuals back in the population. This leaves you with 3/4 bad genes and 1/4 good genes (approximately, given that the number of genes swapped is random).

Typically you would kill off the lower performing individuals, removing their genes from the pool. Then you would breed the better performing individuals to generate the new population. You might also keep some of the very best performers (so as not to lose gains), and/or add a few random individuals (to avoid stagnation).

And the fact that I answered your question does not eliminate micseydel's point that it was a very vague question. Specific questions are better.
if __name__ == "__main__":

    population = Population()
    population.members = Initialization(pop_size)


    for _ in range(generations):
        population.members = Evaluation(population.members)
        population.members = Selection(population.members)
        population.members = TPCrossover(population.members)
        best_of_each_gen.append(population.members[0])
        

    population_visualize = sorted(population.members, key=operator.attrgetter('fitness'))
    print(population_visualize)