daily pastebin goal
4%
SHARE
TWEET

Untitled

a guest Jan 17th, 2019 49 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import numpy as np
  2.  
  3.  
  4. class GeneticAlgorithm():
  5.  
  6.     def __init__(self, chromosomeShape,
  7.                  errorFunction,
  8.                  elitism=1,
  9.                  populationSize=25,
  10.                  mutationProbability=.1,
  11.                  mutationScale=.5,
  12.                  numIterations=10000,
  13.                  errorTreshold=1e-6,
  14.                  ):
  15.  
  16.         self.populationSize = populationSize
  17.         self.p = mutationProbability
  18.         self.numIter = numIterations
  19.         self.e = errorTreshold
  20.         self.f = errorFunction
  21.         self.keep = elitism
  22.         self.k = mutationScale
  23.         self.i = -1
  24.  
  25.         self.population = []
  26.         for _ in range(populationSize):
  27.             chromosome = np.random.randn(chromosomeShape)
  28.  
  29.             fitness = self.calculateFitness(chromosome)
  30.             self.population.append((chromosome, fitness))
  31.  
  32.         self.population = sorted(self.population, key=lambda t: -t[-1])
  33.  
  34.     def run(self, NN):
  35.  
  36.         done = False
  37.         while not done:
  38.             done, iteration, best = self.step()
  39.             if iteration % 100 == 0:
  40.                 print(iteration, 1/best[-1])
  41.             NN.set_weights(best[0])
  42.         NN.set_weights(best[0])
  43.  
  44.     def step(self):
  45.  
  46.         self.i += 1
  47.  
  48.         bestUnits = self.bestN(self.keep)
  49.         isFinished = False
  50.         newPopulation = []
  51.         for bu in bestUnits:
  52.             newPopulation.append(bu)
  53.  
  54.         while not len(newPopulation) == len(self.population):
  55.             parents = self.selectParents()
  56.             child = self.crossover(parents[0], parents[1])
  57.             child = self.mutate(child)
  58.             #child = self.mutate1(child)
  59.             newPopulation.append((child, self.calculateFitness(child)))
  60.  
  61.         self.population = newPopulation
  62.  
  63.         self.population = sorted(self.population, key=lambda t: -t[-1])
  64.  
  65.         bestUnit = self.population[0]
  66.  
  67.         fitness = bestUnit[1]
  68.  
  69.         if self.i == self.numIter or fitness <= self.e:
  70.             isFinished = True
  71.  
  72.         return (isFinished, self.i, bestUnit)
  73.  
  74.     def calculateFitness(self, chromosome):
  75.  
  76.         chromosomeError = self.f(chromosome)
  77.  
  78.         return 1 / chromosomeError
  79.  
  80.     def bestN(self, n):
  81.  
  82.         return self.population[:n]
  83.  
  84.     def best(self):
  85.  
  86.         return self.population[0]
  87.  
  88.     def selectParents(self):
  89.  
  90.         sumFit = 0
  91.         prob = 0
  92.         parents = []
  93.         probabilities = []
  94.         for (unit, fit) in self.population:
  95.             sumFit += fit
  96.         for (unit, fit) in self.population:
  97.             probabilities.append((unit, prob, prob + fit / sumFit))
  98.             prob += fit / sumFit
  99.  
  100.         random1 = np.random.uniform()
  101.         random2 = np.random.uniform()
  102.         for probab in probabilities:
  103.             if (random1 > probab[1] and random1 < probab[2]):
  104.                 parents.append(probab[0])
  105.             if (random2 > probab[1] and random2 < probab[2]):
  106.                 parents.append(probab[0])
  107.             if len(parents) == 2:
  108.                 break
  109.         return parents
  110.  
  111.     def crossover(self, p1, p2):
  112.  
  113.         #child = (p1 + p2) / 2
  114.  
  115.         n = np.random.uniform(0,1)
  116.  
  117.         child = n*p1 + (1-n)*p2
  118.  
  119.         return child
  120.  
  121.     def mutate(self, chromosome):
  122.  
  123.         rand = np.random.uniform()
  124.  
  125.         if rand < 0.33:
  126.             for i in range(0, chromosome.shape[0]):
  127.                 prob = np.random.uniform(0, 1)
  128.                 if prob < self.p:
  129.                     gauss = np.random.normal(0, self.k)
  130.                     chromosome[i] += gauss
  131.             return chromosome
  132.  
  133.         elif 0.33 < rand < 0.66:
  134.             for i in range(0, chromosome.shape[0]):
  135.                 prob = np.random.uniform(0, 1)
  136.                 if prob < self.p:
  137.                     gauss = np.random.normal(0, self.k)
  138.                     chromosome[i] += gauss
  139.             return chromosome
  140.  
  141.         elif 0.66 < rand < 1:
  142.             for i in range(0, chromosome.shape[0]):
  143.                 prob = np.random.uniform(0, 1)
  144.                 if prob < self.p:
  145.                     gauss = np.random.normal(0, self.k)
  146.                     chromosome[i] = gauss
  147.             return chromosome
  148.  
  149.     def mutate1(self, chromosome):
  150.         for i in range(0, chromosome.shape[0]):
  151.             rand = np.random.uniform(0, 1)
  152.             if rand < self.p:
  153.                 rand = np.random.normal(0, self.k)
  154.                 chromosome[i] += rand
  155.         return chromosome
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top