生成遗传算法中适应度比例选择(轮盘赌轮)的概率列表

时间:2017-11-04 18:43:29

标签: python python-3.x genetic-algorithm fitness

首先,如果我的方法过于愚蠢或过于简单,我会道歉,我是一位非常努力进入编程的经济学家,因此我缺乏一些特定的技能。无论如何,我有以下代码:

population = [[[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1], [1], [0]],
 [[0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1], [3], [1]],
 [[0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [4], [2]],
 [[1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0], [3], [3]]]

def ProbabilityList(population):
    fitness = chromosome[2] for chromosome in population
    manipulated_fitness = fitness + 1
    total_weight=sum(manipulated_fitness)
    relative_fitness= [chromosome[1]/total_weight for chromosome in population]
    probabilities= [sum(relative_fitness) for i in range(len(relative_fitness))]
    return (probabilities)

人口的逻辑是[[[individual1],[fitness][counter]],[individual3],[fitness][counter]], and so on...计数器只是一个数字,所以我可以命令个人。

所以我在这种情况下需要的是根据总体适应度创建一个选择概率列表。我还需要在基本适应度上加1,因为将来值可能为零,我不能使用确定性选择方法(也就是说,没有个体可以有0个概率)

有人会知道这样处理它的正确方法吗?

1 个答案:

答案 0 :(得分:1)

您可能会考虑使用的一个库是numpy,它具有完全符合您要求的功能: A weighted version of random.choice

编辑:这是根据您的代码执行此操作的一种方法。

from numpy.random import choice    
def ProbabilityList(population):
    #manipulated fitness in one line
    manipulated_fitness = [chromosome[1]+1 for chromosome in population]
    total_weight=sum(manipulated_fitness)
    #define probabilities - note we should use +1 here too otherwise we won't get a proper distribution
    relative_fitness= [(chromosome[1]+1)/total_weight for chromosome in population]
    #get a list of the ids
    ids = [chromosome[2] for chromosome in population]
    #choose one id based on their relative fitness
    draw = choice(ids, 1, p=relative_fitness)
    #return your choice
    return draw
    #if you want to return the probability distribution you can just return relative_fitness

我还要提出两点建议,让您了解一些稍微复杂的数据结构/方法,这些数据结构/方法可能会让您的生活变得更轻松:字典或类。

编辑:我的意思是做类似的事情:

chromosome_dict={id1:{fitness:4,chromosome:[0,1,1,1,0]},
                 id2:{fitness:3,chromosome:[0,0,0,1,1]}}

这不是出于任何计算原因,而是因为它更易于阅读和操作。