轮盘赌轮选择无序健身值

时间:2017-11-10 15:38:54

标签: python python-3.x selection genetic-algorithm

我需要对GA进行健身比例选择方法,但是我的人口不能松散结构(顺序),在这种情况下,在生成概率时,我相信个体得到了错误的权重,程序是:

population=[[[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1], [6], [0]], 
[[0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1], [4], [1]], 
[[0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [6], [2]],
[[1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0], [4], [3]]]

popultion_d={'0,0,1,0,1,1,0,1,1,1,1,0,0,0,0,1': 6, 
'0,0,1,1,1,0,0,1,1,0,1,1,0,0,0,1': 4, 
'0,1,1,0,1,1,0,0,1,1,1,0,0,1,0,0': 6, 
'1,0,0,1,1,1,0,0,1,1,0,1,1,0,0,0': 4}

def ProbabilityList(population_d):
    fitness = population_d.values()
    total_fit = (sum(fitness))
    relative_fitness = [f/total_fit for f in fitness]
    probabilities = [sum(relative_fitness[:i+1]) for i in range(len(relative_fitness))]
    return (probabilities)

def FitnessProportionateSelection(population, probabilities, number):
    chosen = []
    for n in range(number):
        r = random.random()
        for (i, individual) in enumerate(population):
            if r <= probabilities[i]:
                chosen.append(list(individual))
                break
    return chosen

number=2

人口因素是:[[个人],[健身],[专柜]]

概率函数输出为:[0.42857142857142855, 0.5714285714285714, 0.8571428571428571, 1.0]

我在这里注意到,之前的重量总计为下一个重量,不一定是新月顺序,所以认为对于具有最低适应度的染色体给予更高的权重。

我不想订购,因为我需要稍后按位置索引列表,所以我想我会有错误的匹配。

在这种情况下,任何人都知道可能的解决方案,包或不同方法来执行加权选择吗?

p.s:我知道字典在这里可能是多余的,但是我使用列表本身还有其他一些问题。

编辑:我尝试使用random.choices(),如下所示(使用相对适应性):

def FitnessChoices(population, probabilities, number):
    return random.choices(population, probabilities, number)

但是我收到了这个错误:TypeError: choices() takes from 2 to 3 positional arguments but 4 were given

谢谢!

1 个答案:

答案 0 :(得分:1)

使用random.choices肯定是个好主意。您只需要了解函数调用。您必须指明您的概率是边际还是累积。所以你可以使用

import random

def ProbabilityList(population_d):
    fitness = population_d.values()
    total_fit = sum(fitness)
    relative_fitness = [f/total_fit for f in fitness]
    return relative_fitness

def FitnessChoices(population, relative_fitness, number):
    return random.choices(population, weights = relative_fitness, k = number)

import random

def ProbabilityList(population_d):
    fitness = population_d.values()
    total_fit = sum(fitness)
    relative_fitness = [f/total_fit for f in fitness]
    cum_probs = [sum(relative_fitness[:i+1]) for i in range(len(relative_fitness))]
    return cum_probs

def FitnessChoices(population, cum_probs, number):
    return random.choices(population, cum_weights = cum_probs, k = number)

我建议你看一下python中关键字和位置参数之间的区别。