Python deap.creator.create() Examples
The following are 30
code examples of deap.creator.create().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
deap.creator
, or try the search function
.
Example #1
Source File: base.py From tpot with GNU Lesser General Public License v3.0 | 6 votes |
def _setup_toolbox(self): with warnings.catch_warnings(): warnings.simplefilter('ignore') creator.create('FitnessMulti', base.Fitness, weights=(-1.0, 1.0)) creator.create('Individual', gp.PrimitiveTree, fitness=creator.FitnessMulti, statistics=dict) self._toolbox = base.Toolbox() self._toolbox.register('expr', self._gen_grow_safe, pset=self._pset, min_=self._min, max_=self._max) self._toolbox.register('individual', tools.initIterate, creator.Individual, self._toolbox.expr) self._toolbox.register('population', tools.initRepeat, list, self._toolbox.individual) self._toolbox.register('compile', self._compile_to_sklearn) self._toolbox.register('select', tools.selNSGA2) self._toolbox.register('mate', self._mate_operator) if self.tree_structure: self._toolbox.register('expr_mut', self._gen_grow_safe, min_=self._min, max_=self._max + 1) else: self._toolbox.register('expr_mut', self._gen_grow_safe, min_=self._min, max_=self._max) self._toolbox.register('mutate', self._random_mutation_operator)
Example #2
Source File: 01-reconstruct-with-polygons.py From Hands-On-Genetic-Algorithms-with-Python with MIT License | 6 votes |
def saveImage(gen, polygonData): # only every 100 generations: if gen % 100 == 0: # create folder if does not exist: folder = "images/results/run-{}-{}".format(POLYGON_SIZE, NUM_OF_POLYGONS) if not os.path.exists(folder): os.makedirs(folder) # save the image in the folder: imageTest.saveImage(polygonData, "{}/after-{}-gen.png".format(folder, gen), "After {} Generations".format(gen)) # Genetic Algorithm flow:
Example #3
Source File: symbol_regression.py From Artificial-Intelligence-with-Python with MIT License | 5 votes |
def eval_func(individual, points): # Transform the tree expression in a callable function func = toolbox.compile(expr=individual) # Evaluate the mean squared error mse = ((func(x) - (2 * x**3 - 3 * x**2 + 4 * x - 1))**2 for x in points) return math.fsum(mse) / len(points), # Function to create the toolbox
Example #4
Source File: 02-hyperparameter-tuning-genetic.py From Hands-On-Genetic-Algorithms-with-Python with MIT License | 5 votes |
def main(): # create initial population (generation 0): population = toolbox.populationCreator(n=POPULATION_SIZE) # prepare the statistics object: stats = tools.Statistics(lambda ind: ind.fitness.values) stats.register("max", numpy.max) stats.register("avg", numpy.mean) # define the hall-of-fame object: hof = tools.HallOfFame(HALL_OF_FAME_SIZE) # perform the Genetic Algorithm flow with hof feature added: population, logbook = elitism.eaSimpleWithElitism(population, toolbox, cxpb=P_CROSSOVER, mutpb=P_MUTATION, ngen=MAX_GENERATIONS, stats=stats, halloffame=hof, verbose=True) # print best solution found: print("- Best solution is: ") print("params = ", test.formatParams(hof.items[0])) print("Accuracy = %1.5f" % hof.items[0].fitness.values[0]) # extract statistics: maxFitnessValues, meanFitnessValues = logbook.select("max", "avg") # plot statistics: sns.set_style("whitegrid") plt.plot(maxFitnessValues, color='red') plt.plot(meanFitnessValues, color='green') plt.xlabel('Generation') plt.ylabel('Max / Average Fitness') plt.title('Max and Average fitness over Generations') plt.show()
Example #5
Source File: 02-solve-nurses.py From Hands-On-Genetic-Algorithms-with-Python with MIT License | 5 votes |
def main(): # create initial population (generation 0): population = toolbox.populationCreator(n=POPULATION_SIZE) # prepare the statistics object: stats = tools.Statistics(lambda ind: ind.fitness.values) stats.register("min", numpy.min) stats.register("avg", numpy.mean) # define the hall-of-fame object: hof = tools.HallOfFame(HALL_OF_FAME_SIZE) # perform the Genetic Algorithm flow with hof feature added: population, logbook = elitism.eaSimpleWithElitism(population, toolbox, cxpb=P_CROSSOVER, mutpb=P_MUTATION, ngen=MAX_GENERATIONS, stats=stats, halloffame=hof, verbose=True) # print best solution found: best = hof.items[0] print("-- Best Individual = ", best) print("-- Best Fitness = ", best.fitness.values[0]) print() print("-- Schedule = ") nsp.printScheduleInfo(best) # extract statistics: minFitnessValues, meanFitnessValues = logbook.select("min", "avg") # plot statistics: sns.set_style("whitegrid") plt.plot(minFitnessValues, color='red') plt.plot(meanFitnessValues, color='green') plt.xlabel('Generation') plt.ylabel('Min / Average Fitness') plt.title('Min and Average fitness over Generations') plt.show()
Example #6
Source File: 01-solve-n-queens.py From Hands-On-Genetic-Algorithms-with-Python with MIT License | 5 votes |
def main(): # create initial population (generation 0): population = toolbox.populationCreator(n=POPULATION_SIZE) # prepare the statistics object: stats = tools.Statistics(lambda ind: ind.fitness.values) stats.register("min", np.min) stats.register("avg", np.mean) # define the hall-of-fame object: hof = tools.HallOfFame(HALL_OF_FAME_SIZE) # perform the Genetic Algorithm flow with hof feature added: population, logbook = elitism.eaSimpleWithElitism(population, toolbox, cxpb=P_CROSSOVER, mutpb=P_MUTATION, ngen=MAX_GENERATIONS, stats=stats, halloffame=hof, verbose=True) # print hall of fame members info: print("- Best solutions are:") for i in range(HALL_OF_FAME_SIZE): print(i, ": ", hof.items[i].fitness.values[0], " -> ", hof.items[i]) # plot statistics: minFitnessValues, meanFitnessValues = logbook.select("min", "avg") plt.figure(1) sns.set_style("whitegrid") plt.plot(minFitnessValues, color='red') plt.plot(meanFitnessValues, color='green') plt.xlabel('Generation') plt.ylabel('Min / Average Fitness') plt.title('Min and Average fitness over Generations') # plot best solution: sns.set_style("whitegrid", {'axes.grid' : False}) nQueens.plotBoard(hof.items[0]) # show both plots: plt.show()
Example #7
Source File: 01-solve-mountain-car.py From Hands-On-Genetic-Algorithms-with-Python with MIT License | 5 votes |
def main(): # create initial population (generation 0): population = toolbox.populationCreator(n=POPULATION_SIZE) # prepare the statistics object: stats = tools.Statistics(lambda ind: ind.fitness.values) stats.register("min", numpy.min) stats.register("avg", numpy.mean) # define the hall-of-fame object: hof = tools.HallOfFame(HALL_OF_FAME_SIZE) # perform the Genetic Algorithm flow with hof feature added: population, logbook = elitism.eaSimpleWithElitism(population, toolbox, cxpb=P_CROSSOVER, mutpb=P_MUTATION, ngen=MAX_GENERATIONS, stats=stats, halloffame=hof, verbose=True) # print best solution: best = hof.items[0] print() print("Best Solution = ", best) print("Best Fitness = ", best.fitness.values[0]) # save best solution for a replay: car.saveActions(best)
Example #8
Source File: 02-solve-cart-pole.py From Hands-On-Genetic-Algorithms-with-Python with MIT License | 5 votes |
def randomFloat(low, up): return [random.uniform(l, u) for l, u in zip([low] * NUM_OF_PARAMS, [up] * NUM_OF_PARAMS)] # create an operator that randomly returns a float in the desired range:
Example #9
Source File: 02-solve-cart-pole.py From Hands-On-Genetic-Algorithms-with-Python with MIT License | 5 votes |
def main(): # create initial population (generation 0): population = toolbox.populationCreator(n=POPULATION_SIZE) # prepare the statistics object: stats = tools.Statistics(lambda ind: ind.fitness.values) stats.register("max", numpy.max) stats.register("avg", numpy.mean) # define the hall-of-fame object: hof = tools.HallOfFame(HALL_OF_FAME_SIZE) # perform the Genetic Algorithm flow with hof feature added: population, logbook = elitism.eaSimpleWithElitism(population, toolbox, cxpb=P_CROSSOVER, mutpb=P_MUTATION, ngen=MAX_GENERATIONS, stats=stats, halloffame=hof, verbose=True) # print best solution found: best = hof.items[0] print() print("Best Solution = ", best) print("Best Score = ", best.fitness.values[0]) print() # save best solution for a replay: cartPole.saveParams(best) # find average score of 100 episodes using the best solution found: print("Running 100 episodes using the best solution...") scores = [] for test in range(100): scores.append(cart_pole.CartPole().getScore(best)) print("scores = ", scores) print("Avg. score = ", sum(scores) / len(scores))
Example #10
Source File: 02-OneMax-short.py From Hands-On-Genetic-Algorithms-with-Python with MIT License | 5 votes |
def main(): # create initial population (generation 0): population = toolbox.populationCreator(n=POPULATION_SIZE) # prepare the statistics object: stats = tools.Statistics(lambda ind: ind.fitness.values) stats.register("max", numpy.max) stats.register("avg", numpy.mean) # perform the Genetic Algorithm flow: population, logbook = algorithms.eaSimple(population, toolbox, cxpb=P_CROSSOVER, mutpb=P_MUTATION, ngen=MAX_GENERATIONS, stats=stats, verbose=True) # Genetic Algorithm is done - extract statistics: maxFitnessValues, meanFitnessValues = logbook.select("max", "avg") # plot statistics: sns.set_style("whitegrid") plt.plot(maxFitnessValues, color='red') plt.plot(meanFitnessValues, color='green') plt.xlabel('Generation') plt.ylabel('Max / Average Fitness') plt.title('Max and Average Fitness over Generations') plt.show()
Example #11
Source File: 01-solve-friedman.py From Hands-On-Genetic-Algorithms-with-Python with MIT License | 5 votes |
def main(): # create initial population (generation 0): population = toolbox.populationCreator(n=POPULATION_SIZE) # prepare the statistics object: stats = tools.Statistics(lambda ind: ind.fitness.values) stats.register("min", numpy.min) stats.register("avg", numpy.mean) # define the hall-of-fame object: hof = tools.HallOfFame(HALL_OF_FAME_SIZE) # perform the Genetic Algorithm flow with hof feature added: population, logbook = elitism.eaSimpleWithElitism(population, toolbox, cxpb=P_CROSSOVER, mutpb=P_MUTATION, ngen=MAX_GENERATIONS, stats=stats, halloffame=hof, verbose=True) # print best solution found: best = hof.items[0] print("-- Best Ever Individual = ", best) print("-- Best Ever Fitness = ", best.fitness.values[0]) # extract statistics: minFitnessValues, meanFitnessValues = logbook.select("min", "avg") # plot statistics: sns.set_style("whitegrid") plt.plot(minFitnessValues, color='red') plt.plot(meanFitnessValues, color='green') plt.xlabel('Generation') plt.ylabel('Min / Average Fitness') plt.title('Min and Average fitness over Generations') plt.show()
Example #12
Source File: 02-solve-zoo.py From Hands-On-Genetic-Algorithms-with-Python with MIT License | 5 votes |
def main(): # create initial population (generation 0): population = toolbox.populationCreator(n=POPULATION_SIZE) # prepare the statistics object: stats = tools.Statistics(lambda ind: ind.fitness.values) stats.register("max", numpy.max) stats.register("avg", numpy.mean) # define the hall-of-fame object: hof = tools.HallOfFame(HALL_OF_FAME_SIZE) # perform the Genetic Algorithm flow with hof feature added: population, logbook = elitism.eaSimpleWithElitism(population, toolbox, cxpb=P_CROSSOVER, mutpb=P_MUTATION, ngen=MAX_GENERATIONS, stats=stats, halloffame=hof, verbose=True) # print best solution found: print("- Best solutions are:") for i in range(HALL_OF_FAME_SIZE): print(i, ": ", hof.items[i], ", fitness = ", hof.items[i].fitness.values[0], ", accuracy = ", zoo.getMeanAccuracy(hof.items[i]), ", features = ", sum(hof.items[i])) # extract statistics: maxFitnessValues, meanFitnessValues = logbook.select("max", "avg") # plot statistics: sns.set_style("whitegrid") plt.plot(maxFitnessValues, color='red') plt.plot(meanFitnessValues, color='green') plt.xlabel('Generation') plt.ylabel('Max / Average Fitness') plt.title('Max and Average fitness over Generations') plt.show()
Example #13
Source File: 01-reconstruct-with-polygons.py From Hands-On-Genetic-Algorithms-with-Python with MIT License | 5 votes |
def randomFloat(low, up): return [random.uniform(l, u) for l, u in zip([low] * NUM_OF_PARAMS, [up] * NUM_OF_PARAMS)] # create an operator that randomly returns a float in the desired range:
Example #14
Source File: bit_counter.py From Artificial-Intelligence-with-Python with MIT License | 5 votes |
def create_toolbox(num_bits): creator.create("FitnessMax", base.Fitness, weights=(1.0,)) creator.create("Individual", list, fitness=creator.FitnessMax) # Initialize the toolbox toolbox = base.Toolbox() # Generate attributes toolbox.register("attr_bool", random.randint, 0, 1) # Initialize structures toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_bool, num_bits) # Define the population to be a list of individuals toolbox.register("population", tools.initRepeat, list, toolbox.individual) # Register the evaluation operator toolbox.register("evaluate", eval_func) # Register the crossover operator toolbox.register("mate", tools.cxTwoPoint) # Register a mutation operator toolbox.register("mutate", tools.mutFlipBit, indpb=0.05) # Operator for selecting individuals for breeding toolbox.register("select", tools.selTournament, tournsize=3) return toolbox
Example #15
Source File: moga.py From ocelot with GNU General Public License v3.0 | 5 votes |
def init_deap_functions(self): creator.create("Fitness", base.Fitness, weights=self.weights) creator.create("Individual", list, fitness=creator.Fitness) self.toolbox = base.Toolbox() self.toolbox.register("individual", tools.initIterate, creator.Individual, self.generate_ind) self.toolbox.register("population", tools.initRepeat, list, self.toolbox.individual) self.toolbox.register("evaluate", self.fit_func) if self.penalty != None: self.toolbox.decorate("evaluate", tools.DeltaPenality(self.feasible, self.inf_val))
Example #16
Source File: symbol_regression.py From Artificial-Intelligence-with-Python with MIT License | 5 votes |
def create_toolbox(): pset = gp.PrimitiveSet("MAIN", 1) pset.addPrimitive(operator.add, 2) pset.addPrimitive(operator.sub, 2) pset.addPrimitive(operator.mul, 2) pset.addPrimitive(division_operator, 2) pset.addPrimitive(operator.neg, 1) pset.addPrimitive(math.cos, 1) pset.addPrimitive(math.sin, 1) pset.addEphemeralConstant("rand101", lambda: random.randint(-1,1)) pset.renameArguments(ARG0='x') creator.create("FitnessMin", base.Fitness, weights=(-1.0,)) creator.create("Individual", gp.PrimitiveTree, fitness=creator.FitnessMin) toolbox = base.Toolbox() toolbox.register("expr", gp.genHalfAndHalf, pset=pset, min_=1, max_=2) toolbox.register("individual", tools.initIterate, creator.Individual, toolbox.expr) toolbox.register("population", tools.initRepeat, list, toolbox.individual) toolbox.register("compile", gp.compile, pset=pset) toolbox.register("evaluate", eval_func, points=[x/10. for x in range(-10,10)]) toolbox.register("select", tools.selTournament, tournsize=3) 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.decorate("mate", gp.staticLimit(key=operator.attrgetter("height"), max_value=17)) toolbox.decorate("mutate", gp.staticLimit(key=operator.attrgetter("height"), max_value=17)) return toolbox
Example #17
Source File: robot.py From Artificial-Intelligence-with-Python with MIT License | 5 votes |
def create_toolbox(): global robot, pset pset = gp.PrimitiveSet("MAIN", 0) pset.addPrimitive(robot.if_target_ahead, 2) pset.addPrimitive(Prog().prog2, 2) pset.addPrimitive(Prog().prog3, 3) pset.addTerminal(robot.move_forward) pset.addTerminal(robot.turn_left) pset.addTerminal(robot.turn_right) creator.create("FitnessMax", base.Fitness, weights=(1.0,)) creator.create("Individual", gp.PrimitiveTree, fitness=creator.FitnessMax) toolbox = base.Toolbox() # Attribute generator toolbox.register("expr_init", gp.genFull, pset=pset, min_=1, max_=2) # Structure initializers toolbox.register("individual", tools.initIterate, creator.Individual, toolbox.expr_init) toolbox.register("population", tools.initRepeat, list, toolbox.individual) toolbox.register("evaluate", eval_func) toolbox.register("select", tools.selTournament, tournsize=7) 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) return toolbox
Example #18
Source File: test_algorithms.py From deap with GNU Lesser General Public License v3.0 | 5 votes |
def setup_func_single_obj(): creator.create(FITCLSNAME, base.Fitness, weights=(-1.0,)) creator.create(INDCLSNAME, list, fitness=creator.__dict__[FITCLSNAME])
Example #19
Source File: test_algorithms.py From deap with GNU Lesser General Public License v3.0 | 5 votes |
def setup_func_multi_obj(): creator.create(FITCLSNAME, base.Fitness, weights=(-1.0, -1.0)) creator.create(INDCLSNAME, list, fitness=creator.__dict__[FITCLSNAME])
Example #20
Source File: test_algorithms.py From deap with GNU Lesser General Public License v3.0 | 5 votes |
def setup_func_multi_obj_numpy(): creator.create(FITCLSNAME, base.Fitness, weights=(-1.0, -1.0)) creator.create(INDCLSNAME, numpy.ndarray, fitness=creator.__dict__[FITCLSNAME])
Example #21
Source File: test_benchmarks.py From deap with GNU Lesser General Public License v3.0 | 5 votes |
def setUp(self): @binary.bin2float(0, 1023, 10) def evaluate(individual): """Simplest evaluation function.""" return individual creator.create("FitnessMin", base.Fitness, weights=(-1.0,)) creator.create("Individual", list, fitness=creator.FitnessMin) self.toolbox = base.Toolbox() self.toolbox.register("evaluate", evaluate)
Example #22
Source File: test_pickle.py From deap with GNU Lesser General Public License v3.0 | 5 votes |
def setUp(self): creator.create("FitnessMax", base.Fitness, weights=(1.0,)) creator.create("IndList", list, fitness=creator.FitnessMax) creator.create("IndArray", array.array, typecode='f', fitness=creator.FitnessMax) creator.create("IndNDArray", numpy.ndarray, typecode='f', fitness=creator.FitnessMax) creator.create("IndTree", gp.PrimitiveTree, fitness=creator.FitnessMax) self.toolbox = base.Toolbox() self.toolbox.register("func", func) self.toolbox.register("lambda_func", lambda: "True")
Example #23
Source File: test_creator.py From deap with GNU Lesser General Public License v3.0 | 5 votes |
def test_attribute(): creator.create(CNAME, list, a=1) l = creator.__dict__[CNAME]([1,2,3,4]) assert l.a == 1, "%s, expected %i" % (l.a, 1)
Example #24
Source File: test_creator.py From deap with GNU Lesser General Public License v3.0 | 5 votes |
def test_array(): creator.create(CNAME, array.array, typecode="i") a = creator.__dict__[CNAME]([1,2,3,4]) b = creator.__dict__[CNAME]([5,6,7,8]) a[1:3], b[1:3] = b[1:3], a[1:3] ta = array.array("i", [1,6,7,4]) tb = array.array("i", [5,2,3,8]) assert a == ta, "%s, expected %s" % (a, ta) assert b == tb, "%s, expected %s" % (b, tb)
Example #25
Source File: test_creator.py From deap with GNU Lesser General Public License v3.0 | 5 votes |
def test_numpy_nocopy(): creator.create(CNAME, numpy.ndarray) a = creator.__dict__[CNAME]([1,2,3,4]) b = creator.__dict__[CNAME]([5,6,7,8]) a[1:3], b[1:3] = b[1:3], a[1:3] ta = numpy.array([1,6,7,4]) tb = numpy.array([5,6,7,8]) assert all(a == ta), "%s, expected %s" % (a, ta) assert all(b == tb), "%s, expected %s" % (b, tb)
Example #26
Source File: test_creator.py From deap with GNU Lesser General Public License v3.0 | 5 votes |
def test_numpy_copy(): creator.create(CNAME, numpy.ndarray) a = creator.__dict__[CNAME]([1,2,3,4]) b = creator.__dict__[CNAME]([5,6,7,8]) a[1:3], b[1:3] = b[1:3].copy(), a[1:3].copy() ta = numpy.array([1,6,7,4]) tb = numpy.array([5,2,3,8]) assert all(a == ta), "%s, expected %s" % (a, ta) assert all(b == tb), "%s, expected %s" % (b, tb)
Example #27
Source File: 01-optimize-eggholder.py From Hands-On-Genetic-Algorithms-with-Python with MIT License | 5 votes |
def randomFloat(low, up): return [random.uniform(l, u) for l, u in zip([low] * DIMENSIONS, [up] * DIMENSIONS)] # create an operator that randomly returns a float in the desired range and dimension:
Example #28
Source File: base.py From tpot with GNU Lesser General Public License v3.0 | 5 votes |
def _setup_memory(self): """Setup Memory object for memory caching. """ if self.memory: if isinstance(self.memory, str): if self.memory == "auto": # Create a temporary folder to store the transformers of the pipeline self._cachedir = mkdtemp() else: if not os.path.isdir(self.memory): try: os.makedirs(self.memory) except: raise ValueError( 'Could not create directory for memory caching: {}'.format(self.memory) ) self._cachedir = self.memory self._memory = Memory(location=self._cachedir, verbose=0) elif isinstance(self.memory, Memory): self._memory = self.memory else: raise ValueError( 'Could not recognize Memory object for pipeline caching. ' 'Please provide an instance of joblib.Memory,' ' a path to a directory on your system, or \"auto\".' )
Example #29
Source File: 03-optimize-himmelblau-sharing.py From Hands-On-Genetic-Algorithms-with-Python with MIT License | 5 votes |
def randomFloat(low, up): return [random.uniform(a, b) for a, b in zip([low] * DIMENSIONS, [up] * DIMENSIONS)] # create an operator that randomly returns a float in the desired range and dimension:
Example #30
Source File: 04-optimize-simionescu.py From Hands-On-Genetic-Algorithms-with-Python with MIT License | 5 votes |
def randomFloat(low, up): return [random.uniform(l, u) for l, u in zip([low] * DIMENSIONS, [up] * DIMENSIONS)] # create an operator that randomly returns a float in the desired range and dimension: