2

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

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

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

4

1 回答 1

1

您可能会考虑的一个库是 numpy,它的功能完全符合您的要求: 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]}}

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

于 2017-11-04T20:13:04.177 回答