Skip to content

Commit 2a7707b

Browse files
authored
Add files via upload
1 parent c9d5df7 commit 2a7707b

File tree

2 files changed

+321
-44
lines changed

2 files changed

+321
-44
lines changed

example.py

+7-6
Original file line numberDiff line numberDiff line change
@@ -15,25 +15,26 @@ def fitness_func(solution, solution_idx):
1515
# Calculating the fitness value of each solution in the current population.
1616
# The fitness function calulates the sum of products between each input and its corresponding weight.
1717
output = numpy.sum(solution*function_inputs)
18-
fitness = 1.0 / numpy.abs(output - desired_output)
18+
# The value 0.000001 is used to avoid the Inf value when the denominator numpy.abs(output - desired_output) is 0.0.
19+
fitness = 1.0 / (numpy.abs(output - desired_output) + 0.000001)
1920
return fitness
2021

2122
fitness_function = fitness_func
2223

2324
num_generations = 100 # Number of generations.
24-
num_parents_mating = 7 # Number of solutions to be selected as parents in the mating pool.
25+
num_parents_mating = 10 # Number of solutions to be selected as parents in the mating pool.
2526

2627
# To prepare the initial population, there are 2 ways:
2728
# 1) Prepare it yourself and pass it to the initial_population parameter. This way is useful when the user wants to start the genetic algorithm with a custom initial population.
2829
# 2) Assign valid integer values to the sol_per_pop and num_genes parameters. If the initial_population parameter exists, then the sol_per_pop and num_genes parameters are useless.
29-
sol_per_pop = 50 # Number of solutions in the population.
30+
sol_per_pop = 20 # Number of solutions in the population.
3031
num_genes = len(function_inputs)
3132

3233
init_range_low = -2
3334
init_range_high = 5
3435

3536
parent_selection_type = "sss" # Type of parent selection.
36-
keep_parents = 7 # Number of parents to keep in the next population. -1 means keep all parents and 0 means keep nothing.
37+
keep_parents = -1 # Number of parents to keep in the next population. -1 means keep all parents and 0 means keep nothing.
3738

3839
crossover_type = "single_point" # Type of the crossover operator.
3940

@@ -51,9 +52,9 @@ def callback_generation(ga_instance):
5152

5253
# Creating an instance of the GA class inside the ga module. Some parameters are initialized within the constructor.
5354
ga_instance = pygad.GA(num_generations=num_generations,
54-
num_parents_mating=num_parents_mating,
55+
num_parents_mating=num_parents_mating,
5556
fitness_func=fitness_function,
56-
sol_per_pop=sol_per_pop,
57+
sol_per_pop=sol_per_pop,
5758
num_genes=num_genes,
5859
init_range_low=init_range_low,
5960
init_range_high=init_range_high,

0 commit comments

Comments
 (0)