DEAP:创建具有特定值的个人

时间:2019-11-21 12:34:37

标签: python deap

我有一个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

1 个答案:

答案 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])