Description
Hi guys. I have encountered an issue with the Travis checker that I for some reason can't replicate on my machine. I would like some help, if possible.
I recently rewrote the implementation of the genetic algorithm. The PR is #501. The code for the core algorithm was implemented (mostly, I did make some changes) by someone else before me. Here's the code (I blanked the arguments, since it's too long for Github comments):
def genetic_algorithm( ... ):
"""[Figure 4.8]"""
for i in range(ngen):
new_population = []
for j in range(len(population)):
fitnesses = map(fitness_fn, population)
p1, p2 = weighted_sample_with_replacement(2, population, fitnesses)
child = reproduce(p1, p2)
if random.uniform(0, 1) < pmut:
child = mutate(child, gene_pool)
new_population.append(child)
population = new_population
if f_thres:
fittest_individual = argmax(population, key=fitness_fn)
if fitness_fn(fittest_individual) >= f_thres:
return fittest_individual
return argmax(population, key=fitness_fn)
I would like to bring your attention to the following lines:
fitnesses = map(fitness_fn, population)
and
p1, p2 = weighted_sample_with_replacement(2, population, fitnesses)
With these lines we pick randomly the most fit individuals. This line is called in each iteration. As it is right now there are no issues. Since though population
doesn't change inside each generation, I thought it would be best to put the line outside the nested for loop, like this:
for i in range(ngen):
fitnesses = map(fitness_fn, population)
new_population = []
for j in range(len(population)):
p1, p2 = weighted_sample_with_replacement(2, population, fitnesses)
...
That way we save the time it takes to map fitnesses. When I ran the above in my machine, no errors are thrown. But when Travis checked, it actually threw the following error:
search.py:592: in genetic_algorithm
p1, p2 = weighted_sample_with_replacement(2, population, fitnesses)
utils.py:202: in weighted_sample_with_replacement
return [sample() for _ in range(n)]
utils.py:202: in <listcomp>
return [sample() for _ in range(n)]
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
> return lambda: seq[bisect.bisect(totals, random.uniform(0, totals[-1]))]
E IndexError: list index out of range
I tried to replicate the error but I came up with nothing. Does anyone have any idea why that's happening? I find it weird that it fails when I put the line outside the nested loop and passes when it's inside, since it doesn't make much of a difference, right?
Any help is appreciated.