|
1 | 1 | import ga |
2 | | - |
3 | | -""" |
4 | | -Given the following function: |
5 | | - y = f(w1:w6) = w1x1 + w2x2 + w3x3 + w4x4 + w5x5 + 6wx6 |
6 | | - where (x1,x2,x3,x4,x5,x6)=(4,-2,3.5,5,-11,-4.7) and y=44 |
7 | | -What are the best values for the 6 weights (w1 to w6)? We are going to use the genetic algorithm to optimize this function. |
8 | | -""" |
9 | | - |
10 | | -function_inputs = [4,-2,3.5,5,-11,-4.7] |
11 | | -function_output = 44 # Function output. |
| 2 | +import numpy |
12 | 3 |
|
13 | 4 | num_generations = 50 # Number of generations. |
14 | 5 | sol_per_pop = 8 # Number of solutions in the population. |
|
26 | 17 |
|
27 | 18 | keep_parents = 1 # Number of parents to keep in the next population. -1 means keep all parents and 0 means keep nothing. |
28 | 19 |
|
| 20 | +""" |
| 21 | +Given the following function: |
| 22 | + y = f(w1:w6) = w1x1 + w2x2 + w3x3 + w4x4 + w5x5 + 6wx6 |
| 23 | + where (x1,x2,x3,x4,x5,x6)=(4,-2,3.5,5,-11,-4.7) and y=44 |
| 24 | +What are the best values for the 6 weights (w1 to w6)? We are going to use the genetic algorithm to optimize this function. |
| 25 | +""" |
| 26 | + |
| 27 | +function_inputs = [4,-2,3.5,5,-11,-4.7] # Function inputs. |
| 28 | +desired_output = 44 # Function output. |
| 29 | + |
| 30 | +num_genes = len(function_inputs) |
| 31 | + |
| 32 | +def fitness_func(solution): |
| 33 | + # Calculating the fitness value of each solution in the current population. |
| 34 | + # The fitness function calulates the sum of products between each input and its corresponding weight. |
| 35 | + output = numpy.sum(solution*function_inputs) |
| 36 | + fitness = 1.0 / numpy.abs(output - desired_output) |
| 37 | + return fitness |
| 38 | + |
29 | 39 | # Creating an instance of the GA class inside the ga module. Some parameters are initialized within the constructor. |
30 | 40 | ga_instance = ga.GA(num_generations=num_generations, |
31 | 41 | sol_per_pop=sol_per_pop, |
32 | 42 | num_parents_mating=num_parents_mating, |
33 | | - function_inputs=function_inputs, |
34 | | - function_output=function_output, |
| 43 | + num_genes=num_genes, |
| 44 | + fitness_func=fitness_func, |
35 | 45 | mutation_percent_genes=mutation_percent_genes, |
36 | 46 | mutation_num_genes=mutation_num_genes, |
37 | 47 | parent_selection_type=parent_selection_type, |
|
0 commit comments