Advertisement
Guest User

Untitled

a guest
Jan 20th, 2020
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.57 KB | None | 0 0
  1. import random
  2.  
  3.  
  4. def fitness_function(x, y):
  5. return (x ** 2) + (y ** 2)+1
  6.  
  7.  
  8. def evaluate_generation(population):
  9. scores = []
  10. total = 0
  11. for individual in population:
  12. if len(individual) == 2:
  13. r = -fitness_function(individual[0], individual[1])
  14. scores.append(r)
  15. total += r
  16. else:
  17. print("error: Wrong number of arguments received")
  18. avg = total / len(scores)
  19. return scores, avg
  20.  
  21.  
  22. # Create child from parent
  23. def mutate(individual):
  24. new = []
  25. for attribute in individual:
  26. new.append(attribute + random.normalvariate(0, attribute + .1)) # Random factor of normal distribution
  27. return new
  28.  
  29.  
  30. def find_best(population):
  31. best = None
  32. val = None
  33. for individual in population:
  34. if len(individual) == 2:
  35. r = fitness_function(individual[0], individual[1])
  36. try:
  37. if r < val:
  38. best = individual
  39. val = r
  40. except: # On the first run, set the result as best
  41. best = individual
  42. val = r
  43. else:
  44. print("error: Wrong number of arguments received")
  45.  
  46. return best, val
  47.  
  48.  
  49. # Create a population of p lists of [0, 0, ..., 0] of length n
  50. def initialize(n, p):
  51. pop = [[0] * n]
  52. for i in range(p):
  53. pop.append(mutate(pop[0]))
  54. return pop
  55.  
  56.  
  57. # Handle the output of the genetic algorithm
  58. def termination(best, val, total_iterations, population_size, num_attributes):
  59. best = [round(x, 3) for x in best] # Round for printing
  60. print("Ran", total_iterations, "iterations on a population of", population_size)
  61. print("The optimal input is", best, "with a value of", round(val, 3))
  62.  
  63.  
  64. if __name__ == "__main__":
  65. num_attributes = 2
  66. population_size = 100
  67. total_iterations = 100
  68. population = initialize(num_attributes, population_size)
  69. for iteration in range(total_iterations):
  70. scores, avg = evaluate_generation(population)
  71. deleted = 0
  72. new_population = []
  73. for i in range(len(population)):
  74. if scores[i] < avg:
  75. deleted += 1
  76. else:
  77. new_population.append(population[i])
  78. for i in range(deleted):
  79. new_population.append(
  80. mutate(new_population[i % len(new_population)])) # iterate over population with overflow protection
  81. population = new_population
  82. best, val = find_best(population)
  83. termination(best, val, total_iterations, population_size, num_attributes)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement