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个概率)
有人会知道这样处理它的正确方法吗?
答案 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]}}
这不是出于任何计算原因,而是因为它更易于阅读和操作。