本文整理汇总了Python中deap.creator.create方法的典型用法代码示例。如果您正苦于以下问题:Python creator.create方法的具体用法?Python creator.create怎么用?Python creator.create使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类deap.creator
的用法示例。
在下文中一共展示了creator.create方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _setup_toolbox
# 需要导入模块: from deap import creator [as 别名]
# 或者: from deap.creator import create [as 别名]
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)
示例2: saveImage
# 需要导入模块: from deap import creator [as 别名]
# 或者: from deap.creator import create [as 别名]
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:
开发者ID:PacktPublishing,项目名称:Hands-On-Genetic-Algorithms-with-Python,代码行数:18,代码来源:01-reconstruct-with-polygons.py
示例3: generate_dag
# 需要导入模块: from deap import creator [as 别名]
# 或者: from deap.creator import create [as 别名]
def generate_dag(optimal_indvidual, stage_name, num_nodes):
# create nodes for the graph
nodes = np.empty((0), dtype=np.str)
for n in range(1, (num_nodes + 1)):
nodes = np.append(nodes, ''.join([stage_name, "_", str(n)]))
# initialize directed asyclic graph (DAG) and add nodes to it
dag = DAG()
for n in nodes:
dag.add_node(n)
# split best indvidual found via GA to identify vertices connections and connect them in DAG
edges = np.split(optimal_indvidual, np.cumsum(range(num_nodes - 1)))[1:]
v2 = 2
for e in edges:
v1 = 1
for i in e:
if i:
dag.add_edge(''.join([stage_name, "_", str(v1)]), ''.join([stage_name, "_", str(v2)]))
v1 += 1
v2 += 1
# delete nodes not connected to anyother node from DAG
for n in nodes:
if len(dag.predecessors(n)) == 0 and len(dag.downstream(n)) == 0:
dag.delete_node(n)
nodes = np.delete(nodes, np.where(nodes == n)[0][0])
return dag, nodes
示例4: init_deap_functions
# 需要导入模块: from deap import creator [as 别名]
# 或者: from deap.creator import create [as 别名]
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))
示例5: create_toolbox
# 需要导入模块: from deap import creator [as 别名]
# 或者: from deap.creator import create [as 别名]
def create_toolbox(self):
"""OptiGenAlgNsga2Deap method to create DEAP toolbox
Parameters
----------
self : OptiGenAlgNsga2Deap
Returns
-------
self : OptiGenAlgNsga2Deap
OptiGenAlgNsga2Deap with toolbox created
"""
# Create toolbox
self.toolbox = base.Toolbox()
# Create Fitness and individual
creator.create(
"FitnessMin", base.Fitness, weights=[-1 for _ in self.problem.design_var]
)
creator.create("Individual", list, typecode="d", fitness=creator.FitnessMin)
self.toolbox.register("creator", creator.Individual)
# Register individual and population
self.toolbox.register(
"individual",
create_indiv,
self.toolbox.creator,
self.problem.output,
self.problem.design_var,
)
self.toolbox.register("population", tools.initRepeat, list, self.toolbox.individual)
示例6: geneticAlgorithm
# 需要导入模块: from deap import creator [as 别名]
# 或者: from deap.creator import create [as 别名]
def geneticAlgorithm(X, y, n_population, n_generation):
"""
Deap global variables
Initialize variables to use eaSimple
"""
# create individual
creator.create("FitnessMax", base.Fitness, weights=(1.0,))
creator.create("Individual", list, fitness=creator.FitnessMax)
# create toolbox
toolbox = base.Toolbox()
toolbox.register("attr_bool", random.randint, 0, 1)
toolbox.register("individual", tools.initRepeat,
creator.Individual, toolbox.attr_bool, len(X.columns))
toolbox.register("population", tools.initRepeat, list,
toolbox.individual)
toolbox.register("evaluate", getFitness, X=X, y=y)
toolbox.register("mate", tools.cxOnePoint)
toolbox.register("mutate", tools.mutFlipBit, indpb=0.05)
toolbox.register("select", tools.selTournament, tournsize=3)
# initialize parameters
pop = toolbox.population(n=n_population)
hof = tools.HallOfFame(n_population * n_generation)
stats = tools.Statistics(lambda ind: ind.fitness.values)
stats.register("avg", np.mean)
stats.register("min", np.min)
stats.register("max", np.max)
# genetic algorithm
pop, log = algorithms.eaSimple(pop, toolbox, cxpb=0.5, mutpb=0.2,
ngen=n_generation, stats=stats, halloffame=hof,
verbose=True)
# return hall of fame
return hof
示例7: _setup_memory
# 需要导入模块: from deap import creator [as 别名]
# 或者: from deap.creator import create [as 别名]
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\".'
)
示例8: randomFloat
# 需要导入模块: from deap import creator [as 别名]
# 或者: from deap.creator import create [as 别名]
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:
开发者ID:PacktPublishing,项目名称:Hands-On-Genetic-Algorithms-with-Python,代码行数:6,代码来源:03-optimize-himmelblau-sharing.py
示例9: randomFloat
# 需要导入模块: from deap import creator [as 别名]
# 或者: from deap.creator import create [as 别名]
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:
开发者ID:PacktPublishing,项目名称:Hands-On-Genetic-Algorithms-with-Python,代码行数:6,代码来源:04-optimize-simionescu.py
示例10: main
# 需要导入模块: from deap import creator [as 别名]
# 或者: from deap.creator import create [as 别名]
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 elitism:
population, logbook = elitism.eaSimpleWithElitism(population, toolbox, cxpb=P_CROSSOVER, mutpb=P_MUTATION,
ngen=MAX_GENERATIONS, stats=stats, halloffame=hof, verbose=True)
# print info for best solution found:
best = hof.items[0]
print("-- Best Individual = ", best)
print("-- Best 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()
开发者ID:PacktPublishing,项目名称:Hands-On-Genetic-Algorithms-with-Python,代码行数:36,代码来源:04-optimize-simionescu.py
示例11: main
# 需要导入模块: from deap import creator [as 别名]
# 或者: from deap.creator import create [as 别名]
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 = algorithms.eaSimple(population, toolbox, cxpb=P_CROSSOVER, mutpb=P_MUTATION,
ngen=MAX_GENERATIONS, stats=stats, halloffame=hof, verbose=True)
# print best individual info:
best = hof.items[0]
print("-- Best Ever Individual = ", best)
print("-- Best Ever Fitness = ", best.fitness.values[0])
# plot best solution:
plt.figure(1)
tsp.plotData(best)
# plot statistics:
minFitnessValues, meanFitnessValues = logbook.select("min", "avg")
plt.figure(2)
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')
# show both plots:
plt.show()
开发者ID:PacktPublishing,项目名称:Hands-On-Genetic-Algorithms-with-Python,代码行数:40,代码来源:02-solve-tsp-first-attempt.py
示例12: main
# 需要导入模块: from deap import creator [as 别名]
# 或者: from deap.creator import create [as 别名]
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 = algorithms.eaSimple(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])
print("-- Knapsack Items = ")
knapsack.printItems(best)
# 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()
开发者ID:PacktPublishing,项目名称:Hands-On-Genetic-Algorithms-with-Python,代码行数:38,代码来源:01-solve-knapsack.py
示例13: main
# 需要导入模块: from deap import creator [as 别名]
# 或者: from deap.creator import create [as 别名]
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: ",
test.formatParams(hof.items[0]),
", accuracy = ",
hof.items[0].fitness.values[0])
开发者ID:PacktPublishing,项目名称:Hands-On-Genetic-Algorithms-with-Python,代码行数:30,代码来源:01-optimize-mlp-layers.py
示例14: main
# 需要导入模块: from deap import creator [as 别名]
# 或者: from deap.creator import create [as 别名]
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: \n",
test.formatParams(hof.items[0]),
"\n => accuracy = ",
hof.items[0].fitness.values[0])
开发者ID:PacktPublishing,项目名称:Hands-On-Genetic-Algorithms-with-Python,代码行数:30,代码来源:02-optimize-mlp-hyperparameters.py
示例15: createParticle
# 需要导入模块: from deap import creator [as 别名]
# 或者: from deap.creator import create [as 别名]
def createParticle():
particle = creator.Particle(np.random.uniform(MIN_START_POSITION,
MAX_START_POSITION,
DIMENSIONS))
particle.speed = np.random.uniform(MIN_SPEED, MAX_SPEED, DIMENSIONS)
return particle
# create the 'particleCreator' operator to fill up a particle instance:
开发者ID:PacktPublishing,项目名称:Hands-On-Genetic-Algorithms-with-Python,代码行数:10,代码来源:03-pso-himmelblau.py