Advertisement
Guest User

Untitled

a guest
Feb 10th, 2016
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. from random import randint
  2.  
  3. def create_population(create, pop_size=1000):
  4. """Create population list"""
  5. return [create() for i in xrange(pop_size)]
  6.  
  7. def crossover(combine, population, pop_size):
  8. """Increase population size by combining"""
  9. original_size = len(population)
  10. while len(population) < pop_size:
  11. population.append(combine(population[randint(0, original_size-1)], population[randint(0, original_size-1)]))
  12. return population
  13.  
  14. def mutation(mutate, population, mutation_rate):
  15. """Mutate portion of population"""
  16. for i in xrange(int(len(population) * mutation_rate)):
  17. pos = randint(0, len(population)-1)
  18. population[pos] = mutate(population[pos])
  19. return population
  20.  
  21. def selection(fitness, population):
  22. """Keep best in population"""
  23. return sorted(population, key=lambda x: fitness(x), reverse=False)[:len(population)/2]
  24.  
  25. def main():
  26. """Goal: identify best approximation of pi"""
  27.  
  28. pop_size = 1000 # Number of solutions
  29. mutation_rate = 0.05 # Fraction of population to mutate
  30. epochs = 20 # Number of iterations to run for
  31.  
  32. # Create randomised population
  33. population = create_population(lambda: [randint(1,5000), randint(1,5000)], pop_size)
  34.  
  35. # Run for number of iterations
  36. for epoch in xrange(epochs):
  37.  
  38. # Remove worst solutions
  39. population = selection(lambda x: abs(float(x[0])/(0.0001+x[1]) - 3.14159265), population)
  40.  
  41. # Show the best so far
  42. best = float(population[0][0]) / (0.0001+population[0][1])
  43. error = abs(best - 3.14159265)
  44. print('Epoch %.03d: %f\t(%d / %d)\terror %f' % (epoch, best, population[0][0], population[0][1], error))
  45.  
  46. # Combine solutions to increase population size to original
  47. population = crossover(lambda x, y: [(x[0]+y[0])/2, (x[1]+y[1])/2], population, pop_size)
  48.  
  49. # Mutate some solutions
  50. population = mutation(lambda x: [x[0]+randint(-1,+1), x[1]+randint(-1,+1)], population, mutation_rate)
  51.  
  52. if __name__ == '__main__':
  53. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement