One Max Problem: Short VersionΒΆ

The short one max genetic algorithm example is very similar to one max example. The only difference is that it makes use of the algorithms module that implements some basic evolutionary algorithms. The initialization are the same so we will skip this phase. The algorithms impemented use specific functions from the toolbox, in this case evaluate(), mate(), mutate() and select() must be registered.

toolbox.register("evaluate", evalOneMax)
toolbox.register("mate", tools.cxTwoPoint)
toolbox.register("mutate", tools.mutFlipBit, indpb=0.05)
toolbox.register("select", tools.selTournament, tournsize=3)

The toolbox is then passed to the algorithm and the algorithm uses the registered function.

def main():
    pop = toolbox.population(n=300)
    hof = tools.HallOfFame(1)
    stats = tools.Statistics(lambda ind: ind.fitness.values)
    stats.register("avg", numpy.mean)
    stats.register("std", numpy.std)
    stats.register("min", numpy.min)
    stats.register("max", numpy.max)
    
    pop, log = algorithms.eaSimple(pop, toolbox, cxpb=0.5, mutpb=0.2, ngen=40, 
                                   stats=stats, halloffame=hof, verbose=True)

The short GA One max example makes use of a HallOfFame in order to keep track of the best individual to appear in the evolution (it keeps it even in the case it extinguishes), and a Statistics object to compile the population statistics during the evolution.

Every algorithms from the algorithms module can take these objects. Finally, the verbose keyword indicate wheter we want the algorithm to output the results after each generation or not.

The complete source code: examples/ga/onemax_short.

Previous topic

One Max Problem

Next topic

One Max Problem: Using Numpy

This Page