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



首先,如果我的方法太笨拙或简单化,我深表歉意,我是一名经济学家,非常努力地进入编程领域,因此我缺乏一些特定的技能。无论如何,我有以下代码:

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 个概率)

有谁知道处理这种正确的方法吗?

您可能会

考虑的一个库是numpy,它具有一个完全符合您要求的函数:随机选择的加权版本

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

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]}}

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

最新更新