DEAP工具箱:考虑突变和交叉算子中不同类型和范围的基因

时间:2017-12-08 19:25:52

标签: python-2.7 deap

我正在研究遗传算法,我正在使用DEAP工具箱。 我写了一个初始化染色体的代码,它们的第一个基因是[0.01,2048]范围内的一个浮点数,它们的第二个基因再次漂浮在[0.0001,10]范围内,它们的最后三个基因是布尔值。这是我的代码:

toolbox.register("attr_flt1", random.uniform, 0.01, 2048)
toolbox.register("attr_flt2", random.uniform, 0.0001, 10)
toolbox.register("attr_bool", random.randint, 0, 1)
enter ctoolbox.register("individual", tools.initCycle, creator.Individual,
             (toolbox.attr_flt1, toolbox.attr_flt2, toolbox.attr_bool, toolbox.attr_bool, toolbox.attr_bool),
             n=1)

有一个创建人口的样本:

[1817.2852738610263, 6.184224906600851, 0, 0, 1], [1145.7253307024512, 8.618185266721435, 1, 0, 1], ...

现在,我想通过考虑基因类型和范围的差异来对我的染色体进行突变和交叉。 目前我有一个错误,因为在应用交叉和变异算子后,为染色体的第一个基因产生了0值,这对我的评估函数是错误的。 任何人都可以使用DEAP工具箱来帮助我进行代码选择,变异和交叉,这些工具箱会在最初定义的范围内产生新的种群吗?

1 个答案:

答案 0 :(得分:0)

如果您使用突变算子mutPolynomialBounded(已记录here),则可以指定每个基因的间隔。

按照您指定的边界,也许使用诸如

eta = 0.5 #indicates degree of ressemblance of mutated individual
indpb = 0.1 #probability of individual to be mutated
low = [0.01, 0.0001, 0, 0, 0] #lower bound for each gene
up = [2048, 10, 1, 1, 1] #upper bound for each gene
toolbox.register('mutate', mutPolynomialBounded(individual, eta, low, up, indpb))

作为突变函数将解决您的错误。 这样,第一个基因在区间[0.01, 2048]中,第二个基因在区间[0.0001, 10]中,后三个基因在区间[0, 1]中。


如果您还希望最后三个基因是01(但中间不要有浮点数),那么您可能必须实现自己的突变功能。例如,以下功能将根据您的要求为每个基因选择随机值

def mutRandom(individual, indpb):
    if random.random() < indpb:
        individual[0] = toolbox.attr_flt1()
        individual[1] = toolbox.attr_flt2()
        for i in range(2, 5):
            individual[i] = toolbox.attr_bool()
    return individual,