8000 Add files via upload · ahmedfiz/GeneticAlgorithmPython@962bef9 · GitHub
[go: up one dir, main page]

Skip to content

Commit 962bef9

Browse files
authored
Add files via upload
1 parent 3323f05 commit 962bef9

File tree

2 files changed

+129
-0
lines changed

2 files changed

+129
-0
lines changed

Example_GeneticAlgorithm.py

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
import numpy
2+
import GA
3+
4+
"""
5+
The y=target is to maximize this equation ASAP:
6+
y = w1x1+w2x2+w3x3+w4x4+w5x5+6wx6
7+
where (x1,x2,x3,x4,x5,x6)=(4,-2,3.5,5,-11,-4.7)
8+
What are the best values for the 6 weights w1 to w6?
9+
We are going to use the genetic algorithm for the best possible values after a number of generations.
10+
"""
11+
12+
# Inputs of the equation.
13+
equation_inputs = [4,-2,3.5,5,-11,-4.7]
14+
15+
# Number of the weights we are looking to optimize.
16+
num_weights = 6
17+
18+
"""
19+
Genetic algorithm parameters:
20+
Mating pool size
21+
Population size
22+
"""
23+
sol_per_pop = 8
24+
num_parents_mating = 4
25+
26+
# Defining the population size.
27+
pop_size = (sol_per_pop,num_weights) # The population will have sol_per_pop chromosome where each chromosome has num_weights genes.
28+
#Creating the initial population.
29+
new_population = numpy.random.uniform(low=-4.0, high=4.0, size=pop_size)
30+
print(new_population)
31+
32+
"""
33+
new_population[0, :] = [2.4, 0.7, 8, -2, 5, 1.1]
34+
new_population[1, :] = [-0.4, 2.7, 5, -1, 7, 0.1]
35+
new_population[2, :] = [-1, 2, 2, -3, 2, 0.9]
36+
new_population[3, :] = [4, 7, 12, 6.1, 1.4, -4]
37+
new_population[4, :] = [3.1, 4, 0, 2.4, 4.8, 0]
38+
new_population[5, :] = [-2, 3, -7, 6, 3, 3]
39+
"""
40+
41+
best_outputs = []
42+
num_generations = 1000
43+
for generation in range(num_generations):
44+
print("Generation : ", generation)
45+
# Measuring the fitness of each chromosome in the population.
46+
fitness = GA.cal_pop_fitness(equation_inputs, new_population)
47+
print("Fitness")
48+
print(fitness)
49+
# Selecting the best parents in the population for mating.
50+
parents = GA.select_mating_pool(new_population, fitness,
51+
num_parents_mating)
52+
print("Parents")
53+
print(parents)
54+
55+
# Generating next generation using crossover.
56+
offspring_crossover = GA.crossover(parents,
57+
offspring_size=(pop_size[0]-parents.shape[0], num_weights))
58+
print("Crossover")
59+
print(offspring_crossover)
60+
61+
# Adding some variations to the offsrping using mutation.
62+
offspring_mutation = GA.mutation(offspring_crossover)
63+
print("Mutation")
64+
print(offspring_mutation)
65+
66+
# Creating the new population based on the parents and offspring.
67+
new_population[0:parents.shape[0], :] = parents
68+
new_population[parents.shape[0]:, :] = offspring_mutation
69+
70+
best_outputs.append(numpy.max(numpy.sum(new_population*equation_inputs, axis=1)))
71+
# The best result in the current iteration.
72+
print("Best result : ", numpy.max(numpy.sum(new_population*equation_inputs, axis=1)))
73+
74+
# Getting the best solution after iterating finishing all generations.
75+
#At first, the fitness is calculated for each solution in the final generation.
76+
fitness = GA.cal_pop_fitness(equation_inputs, new_population)
77+
# Then return the index of that solution corresponding to the best fitness.
78+
best_match_idx = numpy.where(fitness == numpy.max(fitness))
79+
80+
print("Best solution : ", new_population[best_match_idx, :])
81+
print("Best solution fitness : ", fitness[best_match_idx])
82+
83+
84+
import matplotlib.pyplot
85+
matplotlib.pyplot.plot(best_outputs)
86+
matplotlib.pyplot.xlabel("Iteration")
87+
matplotlib.pyplot.ylabel("Fitness")
88+

GA.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import numpy
2+
3+
def cal_pop_fitness(equation_inputs, pop):
4+
# Calculating the fitness value of each solution in the current population.
5+
# The fitness function calulates the sum of products between each input and its corresponding weight.
6+
fitness = numpy.sum(pop*equation_inputs, axis=1)
7+
return fitness
8+
9+
def select_mating_pool(pop, fitness, num_parents):
10+
# Selecting the best individuals in the current generation as parents for producing the offspring of the next generation.
11+
parents = numpy.empty((num_parents, pop.shape[1]))
12+
for parent_num in range(num_parents):
13+
max_fitness_idx = numpy.where(fitness == numpy.max(fitness))
14+
max_fitness_idx = max_fitness_idx[0][0]
15+
parents[parent_num, :] = pop[max_fitness_idx, :]
16+
fitness[max_fitness_idx] = -99999999999
17+
return parents
18+
19+
def crossover(parents, offspring_size):
20+
offspring = numpy.empty(offspring_size)
21+
# The point at which crossover takes place between two parents. Usually, it is at the center.
22+
crossover_point = numpy.uint8(offspring_size[1]/2)
23+
24+
for k in range(offspring_size[0]):
25+
# Index of the first parent to mate.
26+
parent1_idx = k%parents.shape[0]
27+
# Index of the second parent to mate.
28+
parent2_idx = (k+1)%parents.shape[0]
29+
# The new offspring will have its first half of its genes taken from the first parent.
30+
offspring[k, 0:crossover_point] = parents[parent1_idx, 0:crossover_point]
31+
# The new offspring will have its second half of its genes taken from the second parent.
32+
offspring[k, crossover_point:] = parents[parent2_idx, crossover_point:]
33+
return offspring
34+
35+
def mutation(offspring_crossover):
36+
# Mutation changes a single gene in each offspring randomly.
37+
for idx in range(offspring_crossover.shape[0]):
38+
# The random value to be added to the gene.
39+
random_value = numpy.random.uniform(-1.0, 1.0, 1)
40+
offspring_crossover[idx, 4] = offspring_crossover[idx, 4] + random_value
41+
return offspring_crossover

0 commit comments

Comments
 (0)
0