为什么我的代码总是用一个或两个字母而不是三个字母来构成一个字符串?

时间:2019-04-09 23:56:59

标签: python-3.x genetic-algorithm

我正在学习如何使用遗传算法。我发现了这个(反复地,很清楚地)简单的练习,它使我了解了如何做的基础(https://blog.sicara.com/getting-started-genetic-algorithms-python-tutorial-81ffa1dd72f9)。

练习的目的是破解功能中提供的“密码”。然后,它会执行整个算法。首先,它使一群随机的字符串组成“密码”的长度。

def generateOrganism(length):
  possible_chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
  i = 0 
  result = ""
  while i < length:
    i += 1
    character = random.choice(possible_chars)
    result += character
  return result


def generatePopulation(sizePopulation, password):
  population = []
  print('Starting Algorithm')
  i = 0
  while i < sizePopulation:
    population.append(generateOrganism(len(password)))
    i += 1
  return population

然后检查每个单词的适合度(由单词与密码的接近程度决定),如下所示:

def fitness (password, test_word):

    if (len(test_word) != len(password)):
        print("taille incompatible")
        return
    else:
        score = 0
        i = 0
        while (i < len(password)):
            if (password[i] == test_word[i]):
                score+=1
            i+=1
        return score * 100 / len(password)


这就是所谓的computePerfPopulation函数,该函数可以创建单词及其适用性的字典。

def computePerfPopulation(population, password):
  populationPerf = {}
  for individual in population:
    populationPerf[individual] = fitness(password, individual)
    if fitness(password, individual) == 100:
      print("EUREKA, WE HAVE CRACKED THE PASSWORD. IT'S '", individual, "'")
      return 'Done'
  print(populationPerf)
  return sorted(populationPerf.items(), key = operator.itemgetter(1), reverse = True)

然后将字典传递给selectFromPopulation函数,该函数选择适应性最好的单词和一些用于“繁殖”的随机单词。

def selectFromPopulation(populationSorted, best_sample, lucky_few):
  nextGen = []
  for i in range(best_sample):
    nextGen.append(populationSorted[i][0])
  for i in range(lucky_few):
    nextGen.append(random.choice(populationSorted)[0])
  random.shuffle(nextGen)
  return nextGen

然后使用以下功能来滋生单词。 这是问题所在。

def createChildren(breeders, num_of_children):
  nextPopulation = []
  for i in range(0, len(breeders) // 2):
    for j in range(0, num_of_children):
      nextPopulation.append(createChild(breeders[i], breeders[len(breeders) -1 -i]))
  print(nextPopulation)
  print(len(nextPopulation))
  return nextPopulation



def createChild(individual1, individual2):
  child = ""
  for i in range(len(individual1)):
    if (int(100) * random.random()) < 50:
      child += individual1[i]

    else:
      print(i)
      print(individual2)
      child += individual2[i]
  return child

然后,一些随机词可能会因下面的函数而发生变异,但这并不完全重要。然后整个过程一直循环直到收到密码

def mutatePopulation(population, chance_mutate): # population is a list

  for i in range(len(population)):
    if int(random.random() * 100) < chance_mutate:
      population[i] = mutateWord(population[i])
  return population


def mutateWord(word):
  possible_chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'

  index_mods = int(random.random() * len(word))
  if index_mods == 0:
    word = random.choice(possible_chars) + word[1:]
    print(word)

  else:
    word = random.choice(possible_chars) + word[index_mods+1:]

  return word

有时,整个项目按预期运行,并且找到了“密码”。但是偶尔我会收到以下错误:

Traceback (most recent call last):
  File "main.py", line 146 in <module>
    project(100, 'lol' 10, 10, 5, 5)
  File "main.py", line 137 in projcet
    remakePopulation = createChildren(newBreeders, num_of_child)
  File "main.py", line 33 in createChildren
    nextPopulation.append(createChild(breeders[i], breeders[len(breeders) - 1 - 1]))
  File "main.py", line 49, in createChild
    child += individual2[i]
IndexError: string index out of range

当我调查此问题时,我开始打印出createChildren函数产生的列表(我将在下面给出总的项目代码),并发现偶尔(在第二个循环或以上,从不在第一个上),有些单词会是 一个或两个字符。 。我怀疑这是因为,当我再次循环它时,我将新的种群插入了computePerfPopulation功能,新的人口与原来的人口不一样,丢掉索引了吗? (我希望这是有道理的)

我不知道是什么原因引起的,如果有人可以告诉我发生了什么,我将不胜感激。 (我知道这已经很久了,但是请耐心等待。)此外,如果您有任何使该代码更好的指针,并且如果您可以给我很好的遗传算法实现资源,我将不胜感激。

(如果您将所有这些代码都放在这里并运行,经过几次尝试,它应该向您显示错误等) 这是完整的项目代码:

import random
import operator


def mutatePopulation(population, chance_mutate): # population is a list

  for i in range(len(population)):
    if int(random.random() * 100) < chance_mutate:
      population[i] = mutateWord(population[i])
  return population


def mutateWord(word):
  possible_chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'

  index_mods = int(random.random() * len(word))
  if index_mods == 0:
    word = random.choice(possible_chars) + word[1:]
    print(word)

  else:
    word = random.choice(possible_chars) + word[index_mods+1:]

  return word




def createChildren(breeders, num_of_children):
  nextPopulation = []
  for i in range(0, len(breeders) // 2):
    for j in range(0, num_of_children):
      nextPopulation.append(createChild(breeders[i], breeders[len(breeders) -1 -i]))
  print(nextPopulation)
  print(len(nextPopulation))
  return nextPopulation



def createChild(individual1, individual2):
  child = ""
  for i in range(len(individual1)):
    if (int(100) * random.random()) < 50:
      child += individual1[i]

    else:
      print(i)
      print(individual2)
      child += individual2[i]
  return child




def selectFromPopulation(populationSorted, best_sample, lucky_few):
  nextGen = []
  for i in range(best_sample):
    nextGen.append(populationSorted[i][0])
  for i in range(lucky_few):
    nextGen.append(random.choice(populationSorted)[0])
  random.shuffle(nextGen)
  return nextGen



def computePerfPopulation(population, password):
  populationPerf = {}
  for individual in population:
    populationPerf[individual] = fitness(password, individual)
    if fitness(password, individual) == 100:
      print("EUREKA, WE HAVE CRACKED THE PASSWORD. IT'S '", individual, "'")
      return 'Done'
  print(populationPerf)
  return sorted(populationPerf.items(), key = operator.itemgetter(1), reverse = True)



def generateOrganism(length):
  possible_chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
  i = 0 
  result = ""
  while i < length:
    i += 1
    character = random.choice(possible_chars)
    result += character
  return result


def generatePopulation(sizePopulation, password):
  population = []
  print('Starting Algorithm')
  i = 0
  while i < sizePopulation:
    population.append(generateOrganism(len(password)))
    i += 1
  return population



def fitness(password, test_word): # fitness function of the algorithm

  if len(test_word) != len(password):
    badFit = 0.0
    return badFit

  else:
    score = 0
    i = 0
    while i < len(password):
      if password[i] == test_word[i]:
        score += 1

      i += 1
  if test_word == password:
    print("SUCCESS")

  fit = (score * 100) / len(password)

  return fit



def project(population_size, password, best_sample, lucky_few, num_of_child, chance_of_mutation):
  password = str(password)
  population = generatePopulation(population_size, password)
  populationSorted = computePerfPopulation(population, password)
  #print(computePerfPopulation(population, password))
  breeders = selectFromPopulation(populationSorted, best_sample, lucky_few)
  nextPopulation = createChildren(breeders, num_of_child)
  nextGeneration = mutatePopulation(nextPopulation, chance_of_mutation)
  while True:
    i = 1
    newPopulationSorted = computePerfPopulation(nextGeneration, password)
    if newPopulationSorted == 'Done':
      break
    newBreeders = selectFromPopulation(newPopulationSorted, best_sample, lucky_few)
    remakePopulation = createChildren(newBreeders, num_of_child)
    nextGeneration = mutatePopulation(remakePopulation, chance_of_mutation)
    print(nextGeneration)
    print(len(nextGeneration))
    input('Press enter to continue')
    i += 1

1 个答案:

答案 0 :(得分:0)

在部分

def mutateWord(word):
    possible_chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'

可能是单个文本而不是数组吗?

赞:

def mutateWord(word):
    possible_chars = [a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,1,2,3,4,5,6,7,8,9,0]

那是一个镜头!