我想在适应度没有增加时停止遗传算法。
我在 python 中使用 DEAP 库。
通常,我有以下日志文件:
gen nevals mean max
0 100 0.352431 0.578592
1 83 -0.533964 0.719633
2 82 -0.567494 0.719633
3 81 -0.396759 0.751318
4 74 -0.340427 0.87888
5 80 -0.29756 0.888443
6 86 -0.509486 0.907789
7 85 -0.335586 1.06199
8 69 -0.23967 1.12339
9 73 -0.10727 1.20622
10 88 -0.181696 1.20622
11 77 -0.188449 1.20622
12 72 0.135398 1.25254
13 67 0.0304611 1.26931
14 74 -0.0436463 1.3181
15 70 0.289306 1.37582
16 79 -0.0441134 1.37151
17 73 0.339611 1.37204
18 68 -0.137938 1.37204
19 76 0.000527522 1.40034
20 84 0.198005 1.40078
21 69 0.243705 1.4306
22 74 0.11812 1.4306
23 83 0.16235 1.4306
24 82 0.270455 1.43492
25 76 -0.200259 1.43492
26 77 0.157181 1.43492
27 74 0.210868 1.43492
我最初设置 ngen = 200,但正如您所看到的,适应度函数在第 22 代达到局部最大值。所以我想在这种情况发生时停止遗传算法。
def main():
random.seed(64)
pop = toolbox.population(n=100)
CXPB, MUTPB = 0.5, 0.2
print "Start of evolution"
fitnesses = list(map(toolbox.evaluate, pop))
for ind, fit in zip(pop, fitnesses):
ind.fitness.values = fit
print " Evaluated %i individuals" % len(pop)
fits = [ind.fitness.values[0] for ind in pop]
g = 0
while max(fits) < 0.67 and g < 1000000:
g = g + 1
print "-- Generation %i --" % g
offspring = toolbox.select(pop, len(pop))
offspring = list(map(toolbox.clone, offspring))
for child1, child2 in zip(offspring[::2], offspring[1::2]):
if random.random() < CXPB:
toolbox.mate(child1, child2)
del child1.fitness.values
del child2.fitness.values
for mutant in offspring:
if random.random() < MUTPB:
toolbox.mutate(mutant)
del mutant.fitness.values
invalid_ind = [ind for ind in offspring if not ind.fitness.valid]
fitnesses = map(toolbox.evaluate, invalid_ind)
for ind, fit in zip(invalid_ind, fitnesses):
ind.fitness.values = fit
pop[:] = offspring
fits = [ind.fitness.values[0] for ind in pop]
print "fitness-- ",max(fits)
print "-- End of (successful) evolution --"
best_ind = tools.selBest(pop, 1)[0]
triangle_to_image(best_ind).save('best.jpg')
当达到所需的适应度值或特定代数结束时,这将停止代码
您可以设置当健身一段时间没有改变时停止,即当它达到局部最大值并卡在那里时
第 12 行当适应度超过 0.67 时,此示例停止然后保存结果
当您不使用名人堂之类的东西时,这是这样做的方法不知道该怎么做,如果你发现它也告诉我
我是一名优秀的程序员,十分优秀!