【问题标题】:How to avoid select two identical parents in genetic algorithm?如何避免在遗传算法中选择两个相同的父母?
【发布时间】: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


【解决方案1】:

在选择第一个选择后,在 select_individual() 中,您遍历同一列表以选择第二个选择。您可以创建一个列表,将 first_pick 从“人口”中排除,然后对其进行迭代。

【讨论】:

  • 您能否告诉我,我可以使用哪些代码或函数将 first_pick 从“人口”列表中排除?
猜你喜欢
  • 2021-11-04
  • 2020-04-14
  • 2012-12-10
  • 2019-05-26
  • 2022-11-29
  • 1970-01-01
  • 2015-03-02
  • 2011-07-07
  • 2016-07-18
相关资源
最近更新 更多