GeneticAlgorithmPython icon indicating copy to clipboard operation
GeneticAlgorithmPython copied to clipboard

User-Defined Parent Selection Operator

Open radwaahmed2132000 opened this issue 2 years ago • 1 comments

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]`

radwaahmed2132000 avatar May 09 '23 22:05 radwaahmed2132000

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])

ahmedfgad avatar May 10 '23 14:05 ahmedfgad