我正在研究一个遗传算法实现,我正在使用DEAP工具箱。我编写了一个代码,初始化染色体,它们的第一个基因是一个浮动数,在0.012048范围内,他们的第二个基因又在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工具箱进行代码选择、变异和交叉,在最初定义的范围内生成新的种群吗?
发布于 2019-11-06 08:21:15
如果您使用突变操作符mutPolynomialBounded (文档化的这里),那么您可以指定每个基因的间隔。
使用您所指示的界限,可能会使用以下内容
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]中。
如果您还希望最后三个基因是0或1 (但不是在两者之间浮动),那么您可能必须实现自己的突变功能。例如,下面的函数将使用您的需求为每个基因选择随机值
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,https://stackoverflow.com/questions/47720921
复制相似问题