Reputation: 11
I'd like to use PyGAD to solve job assignment problem and hope to get the result not only one chromosome but whole population. Such as [[1,1,0,0][0,0,1,1]] represent 4 slots,and 1 in first chromosome mean one guy assigned to those slots,another two slots assign to another guy according to second chromosome.
Follow the tutorial on the PyGAD website (https://pygad.readthedocs.io),am I doing right use initial_population
to generate population?Is it right to use cal_pop_fitness()
function ? I made some tries and still have no idea.
import pygad
import numpy
sol_per_pop = 2
num_genes = 4
pop_size = (sol_per_pop,num_genes)
new_population = numpy.random.randint(low=0,high=2,size=pop_size)
num_generations = 100
num_parents_mating = 2
def fitness_func(solution,solution_idx):
fitness = ga_instance.cal_pop_fitness(new_population)
#do something
ga_instance = pygad.GA(initial_population = new_population,
num_generations=num_generations,
num_parents_mating=num_parents_mating,
sol_per_pop=sol_per_pop,
num_genes=num_genes,
mutation_type=None,
fitness_func=fitness_func)
ga_instance.run()
Upvotes: 1
Views: 1282
Reputation: 866
I have some notes:
cal_pop_fitness()
is not a function. It is a method in the pygad.GA
class.cal_pop_fitness()
method does not accept any parameters. It is not correct to pass the new_population
to it.fitness_func
parameter calls the cal_pop_fitness()
method. In PyGAD, the cal_pop_fitness()
method calls your custom fitness function. Thus, you enter an infinite loop where the 2 functions are calling each other.So, your code cannot work this way.
If you want to get the fitness of the most recent population, you can use the last_generation_fitness
attribute. Just access it within your fitness function:
ga_instance.last_generation_fitness
Note that this attribute is None
for the first generation. So, you can set it to some initial fitness values before calling the run()
method:
ga_instance.last_generation_fitness = numpy.array([1, 1])
Upvotes: 2