无法理解python遗传算法中的错误

时间:2018-02-16 16:31:15

标签: python python-3.x genetic-algorithm

我在YouTube视频中编写了以下代码,该视频是一个简单的遗传算法教程。我试图学习的东西。

from fuzzywuzzy import fuzz
import random
import string

class Agent:
    def __init__(self,length):        #Initialization by using a constructor
        self.string = ''.join(random.choice(string.ascii_letters)for _ in range(length))    # Using random letters to make the initial population
        self.fitness = -1

    def __str__(self):               # Special method to print string and fitness value
        return 'String: ' + str(self.string) + ' Fitness: ' + str(self.fitness)

in_str = None
in_str_len = None
population = 20  #20 agents
generations = 1000

def ga():       # For evolving
    agents = init_agents(population,in_str_len)  # Returns a list of initialized agents
    for gen in range(generations):
        print('Generation: ' + str(generations))
        agents = fitness(agents)
        agents = selection(agents)
        agents = crossover(agents)
        agents = mutation(agents)

        if any(agent.fitness >= 90 for agent in agents): # Ends program if agent reaches fitness of 90
            print('Threshold reached')
            exit()
def init_agents(population,len):
    return[Agent(len) for _ in range(population)]

def fitness(agents):
    for agent in agents:
        agent.fitness = fuzz.ratio(agent.string, in_str)   # Gives fuzzy value when comparing agent string to input string
    return agent

def selection(agents):
    agents = sorted(agents, key=lambda agents: agents.fitness, reverse=True)  # Orders agent fitness from largest to smallest because reverse is given as TRUE
    print ('\n'.join(map(str,agents)))
    agents = agents[:int(0.2 * len(agents))]
    return agents

def crossover(agents):
    offspring = []
    for _ in range(int((population - len(agents))) / 2):
        parent1 = random.choice(agents)
        parent2 = random.choice(agents)
        child1 = Agent(in_str_len)
        child2 = Agent(in_str_len)
        split = random.randit(0, in_str_len)
        child1.string = parent1.string[0:split] + parent2.string[split:in_str_len]
        child2.string = parent2.string[0:split] + parent1.string[split:in_str_len]
        offspring.append(child1)
        offspring.append(child2)
    agents.extend(offspring)
    return agents

def mutation(agents):
    for agent in agents:
        for idx, param in enumerate(agent.string):
            if random.uniform[0.0, 1.0] <= 1.0:
                agent.string = agent.string[0:idx] + random.choice(string.ascii_letters) + agent.string[idx+1, in_str_len] # Insert randomly chosen letter for mutation
    return agents

if __name__ == '__main__':
    in_str = 'TargetWord'
    in_str_len = len(in_str)
    ga()

当我尝试运行程序时出现以下错误。尝试在谷歌和其他论坛上搜索,但没有找到任何可以消除错误的内容。

File "C:/Users/admin/simple_ga.py", line 69, in <module>
    ga()
  File "C:/Users/admin/simple_ga.py", line 23, in ga
    agents = selection(agents)
  File "C:/Users/admin/simple_ga.py", line 39, in selection
    agents = sorted(agents, key=lambda agents: agents.fitness, reverse=True)  # Orders agent fitness from largest to smallest because reverse is given as TRUE
TypeError: 'Agent' object is not iterable

提到错误的原因是什么?

1 个答案:

答案 0 :(得分:2)

您的fitness函数只返回一个Agent,而不是列表。您将该单个结果传递给需要列表的selection函数。