Skip to content

Commit 66ec895

Browse files
committed
Solve duplicates deeply
1 parent d774769 commit 66ec895

File tree

5 files changed

+574
-232
lines changed

5 files changed

+574
-232
lines changed

examples/example_fitness_wrapper.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import pygad
2+
import numpy
3+
4+
"""
5+
All the callback functions/methods in PyGAD have limits in the number of arguments passed.
6+
For example, the fitness function accepts only 3 arguments:
7+
1. The pygad.GA instance.
8+
2. The solution(s).
9+
3. The index (indices) of the passed solution(s).
10+
If it is necessary to pass extra arguments to the fitness function, for example, then follow these steps:
11+
1. Create a wrapper function that accepts only the number of arguments meeded by PyGAD.
12+
2. Define the extra arguments in the body of the wrapper function.
13+
3. Create an inner fitness function inside the wrapper function with whatever extra arguments needed.
14+
4. Call the inner fitness function from the wrapper function while passing the extra arguments.
15+
16+
This is an example that passes a list ([10, 20, 30]) to the inner fitness function. The list has 3 numbers.
17+
A number is randomly selected from the list and added to the calculated fitness.
18+
"""
19+
20+
function_inputs = [4,-2,3.5,5,-11,-4.7]
21+
desired_output = 44
22+
23+
def fitness_func_wrapper(ga_instanse, solution, solution_idx):
24+
def fitness_func(ga_instanse, solution, solution_idx, *args):
25+
output = numpy.sum(solution*function_inputs)
26+
output += numpy.random.choice(args)
27+
fitness = 1.0 / (numpy.abs(output - desired_output) + 0.000001)
28+
return fitness
29+
args = [10, 20, 30]
30+
fitness = fitness_func(ga_instanse, solution, solution_idx, *args)
31+
return fitness
32+
33+
ga_instance = pygad.GA(num_generations=3,
34+
num_parents_mating=5,
35+
fitness_func=fitness_func_wrapper,
36+
sol_per_pop=10,
37+
num_genes=len(function_inputs),
38+
suppress_warnings=True)
39+
40+
ga_instance.run()
41+
ga_instance.plot_fitness()

0 commit comments

Comments
 (0)