1

我想让我的算法做什么

我想在我的人口中拥有一堆随机词作为个体,他们的适应度被比作“最佳”词。如果单词的长度相等,则适应度为+1。对于每个相同的字符,适应度也是 +1,如果它在同一索引中,则 +1.1。

不幸的是,我确实有一段时间了解 deaps 文档。到目前为止,这是我尝试过的。

尝试的代码

from deap import creator
from deap import tools
import random
import time
from create_random_string import get_random_word

ans = "hot"
creator.create("FitnessMax", base.Fitness, weights=(len(ans)+2,))
creator.create("Individual", str, fitness=creator.FitnessMax)

toolbox = base.Toolbox()
toolbox.register("individual",tools.initRepeat,creator.Individual,get_random_word, n=1)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)

def evalOneMax(individual):
    fitness = 0
    if(len(ans)==len(individual)):
        fitness+=1
        for i in range(0,len(ans)):
            if(ans[i]==individual[i]):
                fitness+=1.1

    for i in range(0,len(ans)):
       if individual.find(ans[i]) != -1:
           fitness+=1

    return (fitness,)

#----------
# Operator registration
#----------
# register the goal / fitness function
toolbox.register("evaluate", evalOneMax)

# register the crossover operator
toolbox.register("mate", tools.cxTwoPoint)

# register a mutation operator with a probability to
# flip each attribute/gene of 0.05
toolbox.register("mutate", tools.mutFlipBit, indpb=0.05)

# operator for selecting individuals for breeding the next
# generation: each individual of the current generation
# is replaced by the 'fittest' (best) of three individuals
# drawn randomly from the current generation.
toolbox.register("select", tools.selTournament, tournsize=3)

#----------

if __name__== '__main__':
    random.seed(64)

    pop = toolbox.population(n=50)

    # CXPB  is the probability with which two individuals
    #       are crossed
    #
    # MUTPB is the probability for mutating an individual
    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

代码解释(据我所知)

我首先创建了一个由我的 creator.Individual 类映射到一个随机单词的群体。然后我将它传递到我的评估函数中,以获取每个创建者。个人课程的适应性。在这一步我当然会得到一个错误,因为我没有访问随机词。我的问题是,我怎样才能访问这个词?

选择

我尝试了另一种方法,我只是将单词作为变量保留在 Individual 类中,但这确实与我正在使用的其他 deaps 函数不兼容。使用这种方法,我得到了交叉运算符 deap 给我的错误。我宁愿不必创建自己的交叉运算符。

creator.create("FitnessMax", base.Fitness, weights=(len(ans),))
creator.create("Individual", str, fitness=creator.FitnessMax, word=get_random_word(True,0))

toolbox = base.Toolbox()
toolbox.register("individual",creator.Individual)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)

编辑

更具体地说,如果我在我的 evalOneMax 函数中放置一个“print(individual)”行,它会输出

<generator object initRepeat.<locals>.<genexpr> at 0x1076ffe60>

如何访问映射的随机词以及个人的适应度

4

0 回答 0