Python 3.5 - 遗传算法循环

Python 3.5 - genetic algorithm looping

from pylab import *
import numpy as np
import sys
def initial():
    generation = [0,0,1,1,1,1,1,1,1,0,0,0,0,0]
    generation = generation
    return generation
def fitness(flag):
    global transfer
    transfer = []
    newgeneration1 = pairing()
    scores = [1,2,3,7,6,5,3]
    if flag < 1:
        generation = initial()
    else:
        generation = newgeneration1
    transfer.append(generation)
    transfer.append(scores)
    print(transfer)
    return transfer
def pairing():
    transfer = fitness(i)
    scores = transfer[1]
    generation1 = transfer[0]
    newgeneration = [1,0,1,0,0,0,0,0,1,0,1,1,1,1]
    return newgeneration

initial()
for i in range(3):
   fitness(i)
   pairing()
   if i == 3:
      scores = fitness(i)
      print("The following is the final generation: ")
      print(pairing(i-1))
      print("Here are the scores: ")
      print(scores)
      sys.exit()

以上是我在 python 3.5 中的遗传算法代码的简化版本,当我 运行 这个时,我收到一条错误消息:超出最大递归深度,我试图让它执行一次初始函数,然后在适应度和配对之间循环一定次数的迭代,问题是,pairing() 创建了新一代,而适应度需要采用新一代并确定其适应性,然后将其发送到配对,并创建另一个新一代......等等。你明白了。在此先感谢您的帮助!

问题来了:

那么让我们来看看你的程序...

  • 你先打电话给initial()
  • 接下来你打电话给fitness(i)
  • 在您调用的 fitness 函数中 paring
  • 在您调用的 paring 函数中 fitness
  • 在您调用的 fitness 函数中 paring...

你得到的是一个无限循环,因为 fitnessparing 一直在互相调用

解决方法如下:

def pairing():
    global transfer # transfer is a global variable, you don't need to call a function to get it
    #transfer = fitness(i)
    #scores = transfer[1] # you've already defined these variables, no need to define them again
    #generation1 = transfer[0]
    newgeneration = [1,0,1,0,0,0,0,0,1,0,1,1,1,1]
    return newgeneration

我已经从你的配对函数中删除了一些不必要的行,程序现在可以正常工作了

这是输出:

[[0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0], [1, 2, 3, 7, 6, 5, 3]]
[[1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1], [1, 2, 3, 7, 6, 5, 3]]
[[1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1], [1, 2, 3, 7, 6, 5, 3]]