首先,如果我的方法过于愚蠢或过于简单,我深表歉意,我是一名非常努力学习编程的经济学家,因此我缺乏一些特定的技能。无论如何,我有以下代码:
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]],等等...
只是一个数字,所以我可以对个人进行排序。
所以在这种情况下我需要的是创建一个基于总适应度的选择概率列表。我还需要在基本适应度上加1,因为将来这个值可能为零,我不能使用确定性选择方法(即任何个体都不能有0概率)
谁知道像这样处理它的正确方法?
您可能会考虑的一个库是 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]}}
这不是出于任何计算原因,而是因为它更易于阅读和操作。
我是一名优秀的程序员,十分优秀!