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

ValueError: number of bits must be greater than zero During handling of the above exception, another exception occurred

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

File
"C:\Users\Eshan\AppData\Local\Programs\Python\Python36\lib
andom.py",
line 255, in choice
i = self._randbelow(len(seq)) File"C:\Users\Eshan\AppData\Local\Programs\Python\Python36\lib
andom.py",
line 232, in _randbelow
r = getrandbits(k) # 0 <= r < 2**k ValueError: number of bits must be greater than zero

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File
"C:/Users/Eshan/Desktop/model/simple_ga.py", line 87, in
ga() File"C:/Users/Eshan/Desktop/model/simple_ga.py", line 32, in ga
agents = crossover(agents) File"C:/Users/Eshan/Desktop/model/simple_ga.py", line 62, in crossover
parent1 = random.choice(agents) File"C:\Users\Eshan\AppData\Local\Programs\Python\Python36\lib
andom.py",
line 257, in choice
raise IndexError('Cannot choose from an empty sequence') IndexError: Cannot choose from an empty sequence

Process finished with exit code 1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
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('
'
.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()


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