GeneticAlgorithmPython
GeneticAlgorithmPython copied to clipboard
User-Defined Parent Selection Operator
I am using this example which is provided in documetation , but it gives me an error of parents , it said parents selected are not numpy array, I am using the updated version of pygad
def parent_selection_func(fitness, num_parents, ga_instance):
fitness_sorted = sorted(range(len(fitness)), key=lambda k: fitness[k])
fitness_sorted.reverse()
parents = numpy.empty((num_parents, ga_instance.population.shape[1]))
for parent_num in range(num_parents):
parents[parent_num, :] = ga_instance.population[fitness_sorted[parent_num], :].copy()
return parents, fitness_sorted[:num_parents]`
Sorry this code from the documentation was not updated. This will be fixed in the new release.
For now, please consider changing the type of the returned indices to numpy.ndarray too: numpy.array(fitness_sorted[:num_parents])
This is working well.
def parent_selection_func(fitness, num_parents, ga_instance):
fitness_sorted = sorted(range(len(fitness)), key=lambda k: fitness[k])
fitness_sorted.reverse()
parents = numpy.empty((num_parents, ga_instance.population.shape[1]))
for parent_num in range(num_parents):
parents[parent_num, :] = ga_instance.population[fitness_sorted[parent_num], :].copy()
return parents, numpy.array(fitness_sorted[:num_parents])