ahmedfgad / GeneticAlgorithmPython

Source code of PyGAD, a Python 3 library for building the genetic algorithm and training machine learning algorithms (Keras & PyTorch).
https://pygad.readthedocs.io
BSD 3-Clause "New" or "Revised" License
1.79k stars 451 forks source link

User-Defined Parent Selection Operator #194

Open radwaahmed2132000 opened 1 year ago

radwaahmed2132000 commented 1 year ago

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]`
ahmedfgad commented 1 year ago

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