我正在编写一个遗传算法。有一个由二十个个体组成的种群阵列(每个个体都由一个列表列出(。它绘制三个可能的父母的三个数字(指数(,并选择适应度最高的一个(这是另一个列表(。
问题是在适应度中肯定有一些相同的值(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]]
我希望输出是随机选择索引和最高适应度的列表,但实际输出是一个整数。
最好尽可能避免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])
python list 的 index 方法返回匹配的第一个索引。这就是为什么你没有得到一切。您有以下几种选择:
- 使用 numpy 数组:
import numpy as np
fitness = np.array(fitness)
best = np.argwhere(fitness == value)[:,0] # or np.argmax(fitness)
使用列表(可能更慢(:
best = [ i for i,x in enumerate(fitness) if x == value ]