Get the best individual in each generation with DEAP

48 views Asked by At

I learning genetic algorithms with DEAP and i want to animate how the best individual changes in each generation.

For it i use class Statistics and Multistatistics:

stats = tools.Statistics(lambda ind: ind.fitness.values)
stats.register('min', np.min)
stats.register('mean', np.mean)
history = tools.Statistics(lambda ind: ind)
### Here i get the best individual
history.register('hof', lambda population: list(filter(lambda ind: tspDistance(ind) == np.min(list(map(lambda x: x.fitness.values, population))), population))[0])
mstats = tools.MultiStatistics(fitness=stats, history=history)

hof = tools.HallOfFame(consts.HALL_OF_FAME_SIZE)

population, logbook = algorithms.eaSimple(population, toolbox,
                                              cxpb=consts.P_CROSSOVER, mutpb=consts.P_MUTATION,
                                              ngen=consts.MAX_GENERATIONS, stats=mstats,
                                              halloffame=hof, verbose=True)

But it takes a very long time. Is this a simple way to get best individual in each generation?

1

There are 1 answers

0
Vya4eslav On

Ok, that's too easy...

    hof = tools.HallOfFame(consts.HALL_OF_FAME_SIZE)
    stats = tools.Statistics(lambda ind: ind.fitness.values)
    stats.register('min', np.min)
    stats.register('mean', np.mean)
    history = tools.Statistics(lambda ind: ind)
    history.register('hof', lambda pop: hof[0])
    mstats = tools.MultiStatistics(fitness=stats, history=history)