import numpy from deap import algorithms, base, creator, tools, gp creator.create("FitnessMin", base.Fitness, weights=(-1.0,)) creator.create("Tree", gp.PrimitiveTree, fitness=creator.FitnessMin) pset = gp.PrimitiveSet(name="MAIN", arity=1) pset.addPrimitive(numpy.add, arity=2) pset.addPrimitive(numpy.subtract, arity=2) pset.addPrimitive(numpy.multiply, arity=2) pset.addPrimitive(numpy.negative, arity=1) def evaluateRegression(individual, points, pset): func = gp.compile(expr=individual, pset=pset) sqerrors = (func(points)-(points**4 + points**3 + points**2 + points))**2 return (numpy.sqrt(numpy.sum(sqerrors) / len(points)),) toolbox = base.Toolbox() toolbox.register("expr", gp.genFull, pset=pset, min_=1, max_=3) toolbox.register("individual", tools.initIterate, creator.Tree, toolbox.expr) toolbox.register("population", tools.initRepeat, list,toolbox.individual) toolbox.register("evaluate", evaluateRegression,points=numpy.linspace(-1, 1, 1000), pset=pset) toolbox.register("mate", gp.cxOnePoint) toolbox.register("expr_mut", gp.genFull, min_=0, max_=2) toolbox.register("mutate", gp.mutUniform, expr=toolbox.expr_mut, pset=pset) toolbox.register("select", tools.selTournament, tournsize=3) if __name__ == "__main__": pop = toolbox.population(n=300) algorithms.eaSimple(pop, toolbox, cxpb=0.5, mutpb=0.2, ngen=40) print(tools.selBest(pop, k=1)[0])