如何防止mutGaussian将范围值放入DEAP Python的染色体基因组中

时间:2017-03-17 15:19:50

标签: python genetic-algorithm deap

我用过

toolbox.register("mutate", tools.mutGaussian, mu=1, sigma=1, indpb=10)

突变代码。该函数将值超出范围放入染色体的基因组中。有什么办法可以预防吗?换句话说,有没有办法将每个基因组的价值保持在特定的范围内?

由于

1 个答案:

答案 0 :(得分:1)

此示例取自deap documentation

def checkBounds(min, max):
    def decorator(func):
        def wrapper(*args, **kargs):
            offspring = func(*args, **kargs)
            for child in offspring:
                for i in xrange(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("mutate", checkBounds(MIN, MAX))