如何在python

时间:2017-03-16 18:21:07

标签: python genetic-algorithm evolutionary-algorithm deap

我在Python中使用DEAP包来编写一个优化程序,使用进化算法专门用于遗传算法。

我需要在python中使用list类型创建染色体。这条染色体应该有五个不同范围的漂浮基因(等位基因)。

我的主要问题是创造这样的染色体。但是,如果我可以使用deap包的tools.initRepeat函数,那会更好。

对于所有基因在相同范围内的情况,我们可以使用以下代码:

import random

from deap import base
from deap import creator
from deap import tools

creator.create("FitnessMax", base.Fitness, weights=(1.0,))
creator.create("Individual", list, fitness=creator.FitnessMax)

IND_SIZE=10

toolbox = base.Toolbox()
toolbox.register("attr_float", random.random)
toolbox.register("individual", tools.initRepeat, creator.Individual,
                 toolbox.attr_float, n=IND_SIZE)

我来自here

2 个答案:

答案 0 :(得分:1)

要创建在五个不同范围内具有五个float基因的个体,可以执行以下操作

low = [1, 0, 0, -10, 3] #lower bound for each of the ranges
high = [1234, 1024, 1, 0, 42] #upper bound for each of the ranges

functions = []
for i in range(5):
    def fun(_idx=i):
        return random.uniform(low[_idx], high[_idx])
    functions.append(fun)

toolbox.register("individual", tools.initCycle, creator.Individual,
                 functions,
                 n=1)

toolbox.individual()

答案 1 :(得分:0)

我找到了一个很好的推荐here

def genFunkyInd(icls, more_params):
    genome = list()
    param_1 = random.uniform(...)
    genome.append(param_1)
    param_2 = random.randint(...)
    genome.append(param_2)
    # Many more parameter initialization

    return icls(genome)

The icls  (standing for individual class) parameter should receives the type created with the creator, while all other parameters configuring your ranges can be passed like the more_params argument or with defined constants in your script. Here is how it is registered in the toolbox.

toolbox.register('individual', genFunkyInd, creator.Individual, more_params)

它手动为染色体创建一个类。我不知道它是否是最好的选择,但它可以用来解决我的问题。