原始列表在应用GA运算符后发生突变



应用GA运算符后,原始列表发生突变我使用下面的函数,其中我将rankedChrmos的一部分复制到newpop(列表列表(,然后使用while循环将剩余列表添加到其中,直到newpop的长度等于预定的popSize。但由于某些原因,在while循环实现后,newpop列表发生了变化。在while循环中,我试图实现一些GA运算符,我所做的就是将新的个体附加到newpop列表中,这不应该使newpop发生变异,但它确实发生了变异。不仅如此,即使是rankedChromos也因某种原因发生了变异。

def nextGenPopulation (population, rankedPop, num_robots, crossover_rate):
newpop = 0
fitnessScores = [item[-1] for item in rankedPop ] # extract fitness scores                     
rankedChromos = [item[0] for item in rankedPop ] # extract chromosomes 
popSize = len(population)
newpop = []
print("n fitness", fitnessScores)
newpop.extend(rankedChromos[:int(popSize*0.4)]) # elitism
print("newpop before operations", newpop)
while len(newpop) < popSize:
ind1, ind2 = selectFittest (fitnessScores, rankedChromos)
ind1, ind2 = breed (ind1, ind2, num_robots, crossover_rate)
newpop.append(ind1)
newpop.append(ind2)
print("n newpop after operation", newpop)
return newpop

例如,如果我使用5作为popSize,那么在实现循环之前和之后,newpop的前3个列表应该保持不变,但由于某些原因(下面的示例(,它不一样,我无法理解为什么。如果有任何帮助,我将不胜感激。非常感谢。

newpop before operation =  [[0, 3, 0, 3, 2, 0, 3, 3, 1, 1, 1, 1, 2, 0, 2, 0, 2, 3, 1, 1], [1, 3, 2, 3, 1, 1, 2, 0, 1, 3, 3, 1, 2, 2, 3, 2, 2, 2, 0, 2]]
newpop after operation =  [[0, 3, 0, 3, 2, 0, 3, 3, 1, 1, 1, 1, 1, 1, 2, 0, 0, 3, 1, 1], [1, 3, 2, 3, 1, 1, 2, 0, 1, 3, 3, 1, 2, 2, 3, 2, 2, 2, 0, 2], [0, 3, 0, 3, 2, 0, 3, 3, 1, 1, 1, 1, 1, 1, 2, 0, 0, 3, 1, 1], [2, 0, 0, 1, 0, 1, 2, 2, 1, 0, 0, 2, 2, 0, 3, 3, 2, 0, 0, 0], [2, 0, 0, 1, 0, 1, 2, 2, 1, 0, 0, 2, 2, 0, 3, 3, 2, 0, 0, 0], [0, 3, 0, 3, 2, 0, 3, 3, 1, 1, 1, 1, 1, 1, 2, 0, 0, 3, 1, 1]]

newpop.extend(rankedChromos[:int(popSize*0.4)])它实际上是将第一个int(popSize*0.4) - 1列表的列表引用从rankedChromos复制到newpop中,这意味着对这些列表的rankedChromos的任何修改都将反映在newpop中,很可能是它正在改变rankedChromos的函数selectFittest,因此,您可以在变量newpop中看到突变,你可以使用copy.depopy来消除这种行为

from copy import deepcopy
newpop = deepcopy(rankedChromos[:int(popSize*0.4)])

这里有一个例子来理解您的问题:

list_1 = [[1, 1], [2, 2], [3, 3], [4, 4]] # rankedChromos in your example
list_2 = [] # newpop in your example
list_2.extend(list_1[1: 3])
print('before operation',list_2)
# the function that mutates, selectFittest in your example
def some_fumction(l):
for i in l:
i[1:] = [-9]
some_fumction(list_1)
print('after operation',list_2)

输出:

before operation [[2, 2], [3, 3]]
after operation [[2, -9], [3, -9]]

最新更新