我有一个DEAP工具箱设置
import random
from deap import base, tools, creator, algorithms
toolbox = base.Toolbox()
creator.create("FitnessMax", base.Fitness, weights=(1.0,))
creator.create("Individual", list, fitness=creator.FitnessMax)
toolbox.register("individual", tools.initRepeat, creator.Individual, random.random, n=2)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
我想强迫人口中某些人的价值。为此,我想创建具有给定基因组的个体并将其添加到种群中
pop = toolbox.population(n=10)
new_individual = ?
pop.append(new_individual)
如何定义新个人?做new_individual = toolbox.individual([.1, .2])
不起作用。 new_individual = toolbox.individual(); new_individual.values = [.1, .2]
也没有。如果我这样做了,new_individual = [.1, .2]
就不再具有正确的类型(list
而不是deap.creator.Individual
。
答案 0 :(得分:0)
一种方法如下:new_individual = creator.Individual(individual_values)
from deap import base, creator, tools
import numpy as np
creator.create("FitnessMax", base.Fitness, weights=(1.0,))
creator.create("Individual", list, fitness=creator.FitnessMax)
toolbox = base.Toolbox()
toolbox.register('evaluate', lambda x: fitness_fn(x, **fitness_fn_kwargs))
toolbox.register("attr_int", np.random.randint, low = 0, high = nvals)
toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_int, n = npars)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
pop = toolbox.population(n=pop_size)
pop[0] = creator.Individual(10 * [0])