ValueError:位数必须大于零在处理上述异常时,发生了另一个异常

时间:2017-03-30 09:25:51

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

我正在尝试实现遗传算法,程序在第1代后终止..不知道为什么..代码在下面..提出的xeception是..

  

文件   “C:\用户\峨山\应用程序数据\本地\程序\ Python的\ Python36 \ LIB \ random.py”   第255行,在选择中       i = self._randbelow(len(seq))文件“C:\ Users \ Eshan \ AppData \ Local \ Programs \ Python \ Python36 \ lib \ random.py”,   第232行,在_randbelow       r = getrandbits(k)#0< = r< 2 ** k ValueError:位数必须大于零

     

在处理上述异常期间,发生了另一个异常:

     

Traceback(最近一次调用最后一次):文件   “C:/Users/Eshan/Desktop/model/simple_ga.py”,第87行,       ga()文件“C:/Users/Eshan/Desktop/model/simple_ga.py”,第32行,在ga       agents = crossover(agents)文件“C:/Users/Eshan/Desktop/model/simple_ga.py”,第62行,交叉       parent1 = random.choice(代理)文件“C:\ Users \ Eshan \ AppData \ Local \ Programs \ Python \ Python36 \ lib \ random.py”,   第257行,在选择中       raise IndexError('不能从空序列中选择')IndexError:无法从空序列中选择

     

使用退出代码1完成处理

from fuzzywuzzy import fuzz
import random
import string


class Agent:
    def __init__(self, length):

        self.string = ''.join(random.choice(string.ascii_letters) for _ in range(length))
        self.fitness = -1

    def __str__(self):
        return 'String: ' + str(self.string) + ' Fitness: ' + str(self.fitness)


in_str = 'string-python'
in_str_len = len(in_str)
population = 20
generations = 1000


def ga():

    agents = init_agents(population, in_str_len)

    for generation in range(generations):

        print('Generation: ' + str(generation))

        agents = selection(agents)
        agents = fitness(agents)
        agents = crossover(agents)
        agents = mutation(agents)

        if any(agent.fitness >= 90 for agent in agents):
            print('Threshod met!')
            exit(0)


def init_agents(population, length):
    return [Agent(length) for _ in range(population)]


def fitness(agents):
    for agent in agents:
        agent.fitness = fuzz.ratio(agent.string, in_str)

    return agents


def selection(agents):

    agents = sorted(agents, key=lambda agent: agent.fitness, reverse=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.randint(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)

    return agents


def mutation(agents):

    for agent in agents:
        for idx, param in enumerate(agent.string):
            if random.uniform(0.0, 1.0) <= 0.1:
                agent.string = agent.string[0:idx] + random.choice(string.ascii_letters) + agent.string[idx+1:in_str_len]

    return agents

if __name__ == '__main__':
    in_str = 'string-python'
    in_str_len = len(in_str)
    ga()

1 个答案:

答案 0 :(得分:1)

您的agents看起来是空的,所以当您执行parent1 = random.choice(agents)时,会引发您看到的错误,因为您无法从空列表中随机选择。