One Max Problem: Short VersionΒΆ
The short One Max genetic algorithm example is very similar to the full one
One Max Problem. The only difference is that it makes use of the
algorithms
module which implements some basic evolutionary
algorithms. The initializations are almost the same. We only have to import
some additional packages and modules.
import array
import numpy
from deap import algorithms
In order to use the evolution functions implemented in algorithms
,
we have to register some functions from the tools
module:
evaluate()
, mate()
, mutate()
, and select()
.
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 via stats
it uses the
registered functions.
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 of
extinction), and a Statistics
object to compile
the population statistics during the evolution.
Every algorithm in the algorithms
module can handle
these objects. Finally, the verbose keyword indicates whether we
want the algorithm to output the results after each generation or
not.
The complete source code: examples/%sga/onemax_short.