1

I have this problem with the implementation of the generation of a new population. I have a population of matrices, I defined a fitness function and I need the value of fitness to be as low as possible. So I implemented the function to re-create the population, maintaining only the best individuals from the one before, as it follows:

def new_generation(old_generation, real_coords, elit_rate = ELIT, mutation_rate = MUTATION_RATE, half = HALF, mtype = "strong"):
fit = [fitness(individual, real_coords) for individual in old_generation]
idx = np.argsort(fit)
print(idx)
new_gen = []
for i in range(n_population):
    if i < ELIT:
        new_gen.append(old_generation[idx[i]]) 
    else: 
        new_gen.append(crossover(old_generation[idx[np.random.randint(0,n_population)]], old_generation[idx[np.random.randint(0,n_population)]]))

for i in range(n_population):    
    if np.random.rand() < mutation_rate:
        if i > ELIT:
            new_gen[i] = mutate(new_gen[i],mtype)
print("new gen")
print([fitness(individual, real_coords) for individual in new_gen])
return new_gen

My problem is that the new generation I get is not really ordered with the first ones with the lowest fitness possible! (ELIT is 10 and n_population is 100)

I think my problem is in the part where I do:

for i in range(n_population):
    if i < ELIT:
        new_gen.append(old_generation[idx[i]])

because in my head this should guarantee me to have the first individual in new_gen as I desire.

Where am I wrong? Thank you!

  • I don't have enough context to give you a firm answer but those two lines are wrong: fit = [fitness(individual, real_coords) for individual in old_generation] idx = np.argsort(fit) real_coords is the same for all values;. – Michael Doubez Jun 27 '18 at 12:25
  • @MichaelDoubez Presumably the `fitness` uses the individual's attributes to calculate some coordinates then compares them to the target `real_coords` to generate a fitness, so it doesn't look wrong to me. – Verwirrt Jul 03 '18 at 14:17
  • @Sofia Farina Your code works for me using Python 2.7 with numpy 1.14.3 and some dummy `mutate`, `fitness` and `crossover` functions. Could it simply be that the mutation or cross-over functions are creating individuals which are fitter than your elite 10? This could make it appear to that they elite ten of the last generation aren't the first ten in the new one?. Also I think your line `if i > ELIT:` in the mutate part of the code should be `if i >= ELIT`. – Verwirrt Jul 03 '18 at 14:26

0 Answers0