def main(): random.seed(64) pop = tools.population() hof = halloffame.HallOfFame(1) algorithms.eaSimple(tools, pop, cxpb=0.5, mutpb=0.2, ngen=40, halloffame=hof) logging.info("Best individual is %s, %s", hof[0], hof[0].fitness.values)
creator.create("Individual", gp.PrimitiveTree, fitness=creator.FitnessMax, pset=pset) tools = toolbox.Toolbox() tools.register("expr", gp.generateRamped, pset=pset, type_=pset.ret, min_=1, max_=2) tools.register("individual", creator.Individual, content_init=tools.expr) tools.register("population", list, content_init=tools.individual, size_init=100) tools.register("lambdify", gp.lambdify, pset=pset) def evalSpambase(individual): # Transform the tree expression in a callable function func = tools.lambdify(expr=individual) # Randomly sample 400 mails in the spam database spam_samp = random.sample(spam, 400) # Evaluate the sum of correctly identified mail as spam result = sum(bool(func(*mail[:57])) is bool(mail[57]) for mail in spam_samp) return result, tools.register("evaluate", evalSpambase) tools.register("select", toolbox.selTournament, tournsize=3) tools.register("mate", toolbox.cxTypedTreeOnePoint) tools.register("expr_mut", gp.generateFull, min_=0, max_=2) tools.register("mutate", toolbox.mutTypedTreeUniform, expr=tools.expr_mut) if __name__ == "__main__": pop = tools.population() hof = halloffame.HallOfFame(1) algorithms.eaSimple(tools, pop, 0.5, 0.2, 40, halloffame=hof) logging.info("Best individual is %s, %s", gp.evaluate(hof[0]), hof[0].fitness)