非有序适应度值的轮盘赌选择

Roulette Wheel Selection for non-ordered fitness values

我需要对 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

谢谢!

使用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 中关键字参数和位置参数之间的区别。