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!