首页 > 解决方案 > 如何返回 20 个列表数组中三个中适应度最高的个体?

问题描述

我正在编写遗传算法。有一个由二十个人组成的人口数组(每个人都由一个列表表示)。它绘制了三个可能的父母的三个数字(索引)并选择具有最高适应度的一个(这是另一个列表)。

问题是在适应度中肯定有一些相同的值(11 个可能的值和 20 个项目......)。因此,如果我使用 .index() 方法返回具有该值的第一个。

def genitori(popolazione, fitness):
    def genitore(popolazione, fitness):
        popolazione = popolazione.copy()
        fitness = fitness.copy()
        ran_value = []
        lista = []
        lista_pos = []
        for i in range(0, 3):
            ran_value.append(random.randint(0, 19))        
        print(ran_value)
        for i in ran_value:
            lista.append(fitness[i])
        vincitore = max(lista)
        print(vincitore)
        for i in fitness:
            if i == fitness[vincitore]:
                lista_pos.append(fitness.index(i))


        for i in lista_pos:
            if i in ran_value:
                genitore = popolazione[i]
                return genitore

    gen1 = genitore(popolazione, fitness)
    gen2 = genitore(popolazione, fitness)
    return gen1, gen2

fitness = [5, 5, 4, 5, 4, 3, 5, 4, 6, 7, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
popolazione = [[4, 2, 7, 8, 5, 4, 1, 2, 7, 11, 7, 7, 10, 6, 6, 0],
 [5, 0, 0, 11, 9, 0, 2, 2, 10, 8, 4, 1, 9, 7, 9, 8],
 [4, 4, 5, 3, 9, 8, 11, 1, 7, 4, 11, 8, 7, 3, 3, 7],
 [6, 0, 0, 8, 10, 3, 6, 5, 5, 5, 6, 6, 6, 8, 4, 5],
 [1, 2, 9, 10, 11, 6, 10, 2, 3, 9, 6, 5, 4, 4, 10, 2],
 [9, 11, 3, 5, 10, 2, 5, 8, 6, 4, 11, 10, 0, 1, 8, 4],
 [2, 0, 7, 11, 1, 7, 5, 1, 5, 6, 11, 6, 4, 0, 9, 3],
 [4, 1, 8, 4, 7, 10, 6, 5, 1, 9, 10, 8, 10, 10, 4, 10],
 [2, 7, 7, 6, 6, 1, 3, 1, 7, 6, 11, 1, 3, 7, 5, 2],
 [4, 9, 3, 2, 11, 9, 8, 8, 6, 7, 6, 5, 6, 11, 6, 10],
 [9, 5, 4, 2, 9, 9, 2, 9, 7, 5, 7, 7, 9, 5, 4, 2],
 [2, 5, 7, 9, 9, 9, 9, 11, 0, 9, 11, 0, 2, 11, 9, 7],
 [7, 2, 0, 9, 7, 9, 5, 2, 2, 0, 5, 7, 9, 10, 9, 7],
 [0, 0, 0, 7, 9, 9, 7, 7, 4, 4, 2, 2, 0, 0, 0, 0],
 [4, 7, 9, 9, 9, 11, 0, 0, 0, 2, 11, 11, 9, 7, 7, 11],
 [7, 7, 9, 11, 11, 7, 9, 9, 11, 9, 7, 7, 9, 11, 11, 7],
 [9, 11, 9, 7, 11, 7, 11, 11, 11, 7, 11, 11, 9, 11, 7, 9],
 [4, 11, 0, 2, 0, 11, 9, 9, 0, 4, 2, 0, 11, 0, 2, 4],
 [0, 9, 9, 9, 2, 5, 9, 7, 5, 4, 0, 4, 2, 0, 11, 11],
 [4, 4, 9, 9, 9, 4, 4, 2, 5, 5, 5, 4, 2, 9, 9, 9]]

我希望输出是具有随机选择的索引和最高适应度的列表,但实际输出是一个整数。

标签: pythonlistgenetic-algorithm

解决方案


最好尽可能避免list.index()。我建议你先把人口和健身结合起来:

population_with_fitness = list(zip(fitness, population))

创建一个新的zip元组列表,如下所示:[(fitness1, ind1), (fitness2, ind2), ...]。但它返回一个迭代器,我们必须将其转换为列表。

接下来我们取一个大小为 3 的随机样本,不进行替换(例如,没有重复):

import random
candidates = random.sample(population_with_fitness, 3)

然后按适应度对候选者进行排序:

candidates.sort()
winner_fitness, winner_genes = candidates[-1]
return winner_genes

这是因为 Python 的 sort() 将逐个元素地比较元组。该列表将首先按适应度排序,然后按个体人口成员排序。

对于 GA,如果您期望会出现相等的适应度值,您可能希望保持顺序随机化。这可以这样解决:

candidates.sort(key=lambda x: x[0])

推荐阅读