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

2024-04-23 12:56:20 发布

您现在位置:Python中文网/ 问答频道 /正文

首先,我很抱歉,如果我的方法太愚蠢或过于简单,我是一个经济学家,非常努力地进入编程,因此我缺乏一些具体的技能。不管怎样,我有以下代码:

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

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


Tags: 方法inforcounter概率totalsumpopulation
1条回答
网友
1楼 · 发布于 2024-04-23 12:56:20

您可以考虑的一个库是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

对于稍微复杂一点的数据结构/方法,我也提出两个建议:字典或类。在

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

^{pr2}$

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

相关问题 更多 >