Created
January 25, 2020 22:16
-
-
Save pourmand1376/c70be1698991d3b337dc74fd55cfda4c to your computer and use it in GitHub Desktop.
Minimizing Math Function with Genetic Algorithm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import math | |
import random | |
import numpy | |
def calculateCost(x,y): | |
return -0.0001*(( | |
math.fabs( | |
math.sin(x)*math.sin(y)*math.exp( | |
math.fabs( | |
100 - math.sqrt(x**2+y**2)/math.pi | |
) | |
) | |
)+1 | |
)**0.1) | |
def calculate_fitness_for_all(): | |
global fitness | |
fitness = [] | |
for item in population: | |
x,y = item | |
cost = calculateCost(x,y) | |
fitness.append(cost) | |
def choose_best_of_generation(count): | |
parents = numpy.empty((count,2)) | |
for parent in range(count): | |
max_fitness_idx = numpy.where(fitness == numpy.min(fitness)) | |
max_fitness_idx = max_fitness_idx[0][0] | |
parents[parent] = population[max_fitness_idx] | |
fitness[max_fitness_idx] = 99999999999 | |
return parents | |
def bring_child(pop,count): | |
value = 0 | |
while value < population_size - mutation_size - 1: | |
x_1, y_1 = pop[value] | |
x_2, y_2 = pop[value + 1] | |
pop[value] = (x_1, y_2) | |
pop[value + 1] = (x_2, y_1) | |
value = value + 2 | |
return pop | |
def genetic_algorithm(): | |
global population | |
iteration = 1 | |
while iteration<100: | |
calculate_fitness_for_all() | |
new_population=choose_best_of_generation(population_size-mutation_size) | |
new_population = bring_child(new_population,population_size-mutation_size-1) | |
pop=numpy.empty((population_size,2)) | |
for item in range(len(new_population)): | |
pop[item]=new_population[item] | |
for item in range(mutation_size): | |
x,y=new_population[item] | |
x =x+random.random()*2-1 | |
y= y+random.random()*2-1 | |
pop[item+population_size-mutation_size]=(x,y) | |
population = pop | |
iteration = iteration + 1 | |
mutation_size = 20 | |
range_value = 50 | |
population_size = 100 | |
pop_size = (population_size,2) | |
population = numpy.random.uniform(low = -1*range_value, | |
high = range_value, | |
size = pop_size) | |
#print(population) | |
fitness = [] | |
genetic_algorithm() | |
calculate_fitness_for_all() | |
max_fitness_idx = numpy.where(fitness == numpy.min(fitness)) | |
max_fitness_idx = max_fitness_idx[0][0] | |
print("x,y: ",population[max_fitness_idx],"value: ",fitness[max_fitness_idx]) | |
#print(population) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment