0

我试图在 python 中实现轮盘选择。我很困惑实现它。这是我的代码;我希望有一个人可以帮助我。

    fitness = [ind.fitness for ind in self.population] 
    total_fit = float(sum(fitness))
    relative_fitness = [f/total_fit for f in fitness]
    probabilities = [sum(relative_fitness[:i+1]) 
                 for i in range(len(relative_fitness))]
    
    print("population : ",self.population)
    print("end")
    new_pop = []

    for n in range(len(self.population)):
        r = random.random()
        for (i, individual) in self.population[n]:
            if r <= probabilities[i]:
                new_pop.append(individual)
                break

    print("new_pop")
    print(new_pop)

我的错误

这是我的回溯错误

     TypeError                                 Traceback (most recent call 
     last)
     <ipython-input-18-1ad9ce8eb687> in <module>
       19 
       20     while generation.generation_number < number_generation:
  ---> 21         generation.generate()
       22         if generation.generation_number == number_generation:
       23             # Last generation is the phase

     <ipython-input-17-ed4b4c1175ed> in generate(self)
       92         for n in range(len(self.population)):
       93             r = random.random()
  ---> 94             for (i, individual) in self.population[n]:
       95                 if r <= probabilities[i]:
       96                     new_pop.append(individual)

     TypeError: 'Organism' object is not iterable
4

1 回答 1

0

你的内循环没有任何意义。您正在对单个总体成员进行迭代,然后尝试将其解压缩为一对值。我认为这两种方法都行不通。

我认为您想要for i, individual in enumerate(self.population)添加enumerate和不使用索引[n]

于 2021-03-05T04:24:55.290 回答