Following the DEAP tutorial, I am trying to use multiple statistics.
import numpy as np
import random
from deap import base, creator, tools, algorithms
# Define toolbox
toolbox = base.Toolbox()
creator.create("FitnessMin", base.Fitness, weights=(-1.0,))
creator.create("Individual", list, fitness=creator.FitnessMin)
IND_SIZE=5
toolbox.register("individual", tools.initRepeat, creator.Individual, random.random, n=IND_SIZE)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
popul = toolbox.population(n=7)
def evaluate(individual):
a = sum(individual)
b = len(individual)
return (a / b,)
toolbox.register('evaluate', evaluate)
toolbox.register('mutate', tools.mutGaussian, mu=0.0, sigma=0.2, indpb=0.1)
toolbox.register('mate', tools.cxUniform, indpb=0.4)
toolbox.register('select', tools.selBest)
# Define statistical tools
stats_fit = tools.Statistics(key=lambda ind: ind.fitness.values)
stats_size = tools.Statistics(key=len)
mstats = tools.MultiStatistics(fitness=stats_fit, size=stats_size)
mstats.register("avg", np.mean)
mstats.register("std", np.std)
# Run algorithm
popul, mlogbook = algorithms.eaSimple(popul, toolbox, cxpb=0.5, mutpb=0.2, ngen=10,
stats=mstats, verbose=True)
This prints the statistics on screen.
The documentation states that
The multi-statistics object can be given to an algorithm [...] using the exact same procedure as the simple statistics.
But when I try to access the logbook, it returns a list of None
.
In: mlogbook.select("avg")
Out: [None, None, None, None, None, None, None, None, None, None, None]
If I use regular statistics rather than multiple statistics, I do not have this problem: logbook.select("avg")
returns a list of floats.
How can I access the recorded statistics when using multiple statistics?
It is necessary to specify the chapter from which selecting the statistics. For instance,
mlogbook.chapters["fitness"].select("avg")
returns the expected list of the average value of the fitness across generations.