1
+ import pandas as pd
2
+ import numpy as np
3
+ import pygad
4
+ import math
5
+ import warnings
6
+ warnings .filterwarnings ("ignore" )
7
+
8
+ df = pd .read_excel ('products.xlsx' )
9
+ obj = np .array (df ['Product' ])
10
+ space = np .array (df ['Space' ])
11
+ quantity = np .array (df ['Quantity' ])
12
+
13
+ gene_space = [range (i ) for i in quantity ]
14
+
15
+ function_inputs = space # Function space.
16
+ desired_output = 4 # volume capacity we want to reach.
17
+ sol_per_population = int (math .pow (2 ,11 )) # 2^11 number of sample in the initial population
18
+
19
+
20
+ def fitness_func (solution , solution_idx ):
21
+ """This function calculates the total fitness value by summing the product of
22
+ each input and its corresponding space.
23
+ """
24
+ output = np .sum (solution * function_inputs )
25
+ if (output > desired_output ): # discard a sample if the sum is more than the space available
26
+ fitness = 0.0
27
+ else :
28
+ # The value 0.000001 is used to avoid the Inf value when the denominator numpy.abs(output - desired_output) is 0.0.
29
+ fitness = 1.0 / (np .abs (output - desired_output ) + 0.000001 )
30
+ return fitness
31
+
32
+ def print_selected_obj (ga_instance ,obj ,space ):
33
+
34
+ """This function generates all van loading combinations
35
+ considering capacity, weight and size. It returns a list of possible combinations.
36
+ """
37
+ solution ,_ ,_ = ga_instance .best_solution ()
38
+ solution = np .array (solution ).astype (float )
39
+ print ('\n ' )
40
+ print (f'The optimal sum is { np .sum (solution * space )} ' )
41
+ print ('\n ' )
42
+ print (f'The maximun price is { np .sum (solution * quantity )} ' )
43
+ print ('\n ' )
44
+ print (f'object selected { obj [np .where (solution != 0 )]} ' )
45
+ print ('\n ' )
46
+
47
+
48
+
49
+ def save_model (ga_instance ):
50
+ filename = 'genetic'
51
+ ga_instance .save (filename = filename )
52
+
53
+
54
+ def plot_fitnes (ga_instance ):
55
+ ga_instance .plot_fitness (title = "PyGAD with Adaptive Mutation" , linewidth = 5 )
56
+
57
+
58
+ def show_best_genes (ga_instance ):
59
+ """The function will identify the genes (inputs) with
60
+ the highest fitness value and display them as the best options.
61
+ """
62
+ solution , solution_fitness , solution_idx = ga_instance .best_solution ()
63
+
64
+ print ('\n ' )
65
+ print ("Parameters of the best solution : {solution}" .format (solution = solution ))
66
+ print ("Fitness value of the best solution = {solution_fitness}" .format (solution_fitness = solution_fitness ))
67
+
68
+ print ('\n ' )
69
+
70
+
71
+ # Creating an instance of the GA class inside the ga module. Some parameters are initialized within the constructor.
72
+ ga_instance = pygad .GA (num_generations = 100 ,
73
+ fitness_func = fitness_func ,
74
+ num_parents_mating = 2 ,
75
+ sol_per_pop = sol_per_population ,
76
+ num_genes = len (function_inputs ),
77
+ mutation_type = "adaptive" ,
78
+ mutation_num_genes = (3 , 1 ),
79
+ gene_type = int ,
80
+ parallel_processing = 4 ,
81
+ gene_space = gene_space ,
82
+ keep_elitism = 2 ,
83
+ stop_criteria = ["saturate_7" ])
84
+
85
+
86
+
87
+
88
+ if __name__ == '__main__' :
89
+ # Running the GA to optimize the parameters of the function.
90
+ ga_instance .run ()
91
+
92
+ print_selected_obj (ga_instance ,obj ,space )
93
+
94
+ show_best_genes (ga_instance )
95
+ #Let's save the model.
96
+
97
+ save_model (ga_instance )
98
+ plot_fitnes (ga_instance )
99
+
0 commit comments