def checkBounds(min, max):
def decorator(func):
def wrapper(*args, **kargs):
offspring = func(*args, **kargs)
for child in offspring:
for i in range(len(child)):
if child[i] > max:
child[i] = max
elif child[i] < min:
child[i] = min
return offspring
return wrapper
return decorator
toolbox.register("mate", tools.cxBlend, alpha=0.2) toolbox.register("mutate", tools.mutGaussian, mu=0, sigma=2)
toolbox.decorate("mate", checkBounds(MIN, MAX)) toolbox.decorate("变异", checkBounds(MIN, MAX))
这是代码(https://deap.readthedocs.io/en/master/tutorials/basic/part2.html#tool-decoration),它允许我们在 GA(遗传算法)的进化过程中设定界限。
假设我的后代人口总是触及界限。那么我该如何更新我的界限(最小值和最大值)?问题是 mutate 函数被更早地修饰了。我是否必须再次使用 decorate 语句来更改边界?
能够在进化过程中更改最小值和最大值的方法真的很有帮助