[英]The original list is mutated after applying GA operators
在应用 GA 运算符后,原始列表发生了变化我正在使用下面的函数,我将rankedChromos 的一部分复制到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
例如,如果我为 popSize 使用 5,则 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)])
它实际上是从复制的列表的参考文献rankedChromos
用于第一int(popSize*0.4) - 1
列出成newpop
,这意味着对于任何修改rankedChromos
对于那些列表将反映在newpop
,很可能是函数selectFittest
它正在改变rankedChromos
,因此,您会在变量newpop
看到突变,您可以使用copy.deepcopy来消除这种行为
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]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.