【发布时间】:2021-08-31 13:55:54
【问题描述】:
我是遗传算法的新手,并试图找到一种避免选择两个相同父母的方法,但我没能做到。
假设初始种群为
[[0,0,0,0,1],[0,0,0,1,0],[0,0,1,0,0],[[0,1,0,0,0].
假设每个人的适应度为[2,3,4,5]。
选择父母的代码如下:
def select_individual(population, scores, k=4):
first_pick = np.random.randint(0,len(population))
for second_pick in np.random.randint(0,len(population),k-1):
if scores[second_pick] < scores[first_pick]:
winner = second_pick
else:
winner = first_pick
return population[winner,:]
当我尝试使用下面显示的代码检索两个父母时,它有时会返回两个相同的父母。
for i in range(0, len(population),2):
# Selection
parents = [select_individual(population, scores) for _ in range(len(population))]
parent_1 = parents [i]
parent_2 = parents [i+1]
print('Parent_1: ',np.round(parent_1,2))
print('Parent_2: ',np.round(parent_2,2))
其中一个输出,例如,如下所示:
Parent_1: [0,0,0,1,0]
Parent_2: [0,0,0,1,0]
Parent_1: [0,0,1,0,0]
Parent_2: [0,0,1,0,0]
Or
Parent_1: [0,0,0,1,0]
Parent_2: [0,0,1,0,0]
Parent_1: [0,0,0,1,0]
Parent_2: [0,0,1,0,0]
您能否告诉我代码有什么问题以及为什么两个选定的父母最终是相同的? 非常感谢!
【问题讨论】:
-
为什么不直接做
parents = random.sample(population, 2)? -
这是因为我需要先在初始种群中选择两个个体,然后比较两个选择的个体的适应度。选择适应度较高的个体作为父母。我想要的不是随机选择两个人作为父母。
标签: python