Skip to content

Instantly share code, notes, and snippets.

@ahmdrz
Created December 17, 2017 07:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahmdrz/3c15109fce6fd7feac4617f3316ed78b to your computer and use it in GitHub Desktop.
Save ahmdrz/3c15109fce6fd7feac4617f3316ed78b to your computer and use it in GitHub Desktop.
import random
import copy
import matplotlib.pyplot as plt
class GeneticAlgorithm:
def __init__(self):
self.chromosome_length = 50
self.population = []
self.n = 20
self.crossovers = 5
self.mutations = 5
self.iterator = 0
self.max_iterator = 500
self.selection_cmp = None
def initial(self):
for i in range(self.n):
self.population.append([random.randrange(-5, 5) for _ in range(self.chromosome_length)])
def stop_condition(self):
return self.iterator > self.max_iterator
def do_crossover(self):
chromo_a = self.population[random.randrange(0, self.n / 2)]
chromo_b = self.population[random.randrange(self.n / 2, self.n)]
random_index = random.randrange(self.chromosome_length)
new_chromo_a = chromo_a[:random_index] + chromo_b[random_index:]
new_chromo_b = chromo_b[:random_index] + chromo_a[random_index:]
self.population.append(new_chromo_a)
self.population.append(new_chromo_b)
def do_mutation(self):
for _ in range(self.mutations):
chromo = copy.copy(self.population[random.randrange(len(self.population))])
index = random.randrange(len(chromo) - 1)
chromo[index] += random.randrange(-5, 5)
self.population.append(chromo)
def do_selection(self):
self.population.sort(cmp=self.selection_cmp)
self.population = self.population[:self.n]
@staticmethod
def fitness(chromo):
result = 0
for chromosome in chromo:
result += 3 * (chromosome ** 4) - 4 * (chromosome ** 2) + 3 * chromosome - 7
return result
def __iter__(self):
return self
def next(self):
if self.iterator < self.max_iterator:
i = self.iterator
self.iterator += 1
return i
else:
raise StopIteration()
if __name__ == "__main__":
perfect_fitness_list = []
ga = GeneticAlgorithm()
ga.initial()
ga.selection_cmp = lambda x, y: ga.fitness(x) - ga.fitness(y)
for iterator in ga:
ga.do_crossover()
ga.do_mutation()
ga.do_selection()
fitness_list = [ga.fitness(a) for a in ga.population]
fitness = max(fitness_list)
perfect_fitness_list.append([ga.iterator, fitness])
fig, ax = plt.subplots()
ax.plot([a[0] for a in perfect_fitness_list], [a[1] for a in perfect_fitness_list])
ax.set(xlabel='iterates', ylabel='perfect fitness', title='Genetic algorithm')
fig.savefig("plot.png")
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment