Advertisement
Guest User

Untitled

a guest
Aug 17th, 2019
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.77 KB | None | 0 0
  1. import operator
  2. import random
  3.  
  4.  
  5. # an individual with bigger fitness is more likely to succeed.
  6. def fitness(password, test_word):
  7. if len(test_word) != len(password):
  8. return
  9. score = 0
  10. for i in range(len(password)):
  11. if password[i] == test_word[i]:
  12. score += 1
  13. return score * 100 / len(password)
  14.  
  15.  
  16. # creating individuals (population)
  17. # motivation: DNA is composed of genes and each of them come from different alleles (versions of genes)
  18. # in this case each character is a gene and value of the letter is the allele
  19. # criteria: each individual has a good shape (word of size N) and population can cover all posibilities of words of size N
  20. # first population: should cover all possibilities and shouldn't be biased.
  21.  
  22.  
  23. def generate_first_population(size, password):
  24. def generate_word(length):
  25. alphabet = "abcdefghijklmnopqrstuvwxyz! "
  26. return "".join([random.choice(alphabet) for item in [0] * len(target)])
  27.  
  28. return [generate_word(len(password)) for i in range(size)]
  29.  
  30.  
  31. # Selection: From one generation to the next
  32. # 1. select a specific part of previous generatic
  33. # 2. combine breeders into next batch
  34.  
  35.  
  36. def sort_population_by_fitness(population, password):
  37. performance = {}
  38. for individual in population:
  39. performance[individual] = fitness(password, individual)
  40. return sorted(performance.items(), key=operator.itemgetter(1), reverse=True)
  41.  
  42.  
  43. def select_breeders(sorted_population, take_best, take_lucky):
  44. next_generation = []
  45. for i in range(take_best):
  46. next_generation.append(sorted_population[i][0])
  47. for i in range(take_lucky):
  48. next_generation.append(random.choice(sorted_population)[0])
  49. random.shuffle(next_generation)
  50. return next_generation
  51.  
  52.  
  53. # Breeding
  54.  
  55.  
  56. def create_children(breeders, num_children):
  57. def create_child(individual_1, individual_2):
  58. child = ""
  59. for i in range(len(individual_1)):
  60. if int(100 * random.random()) < 50:
  61. child += individual_1[i]
  62. else:
  63. child += individual_2[i]
  64. return child
  65.  
  66. next_population = []
  67. for i in range(len(breeders) // 2):
  68. for j in range(num_children):
  69. next_population.append(
  70. create_child(breeders[i], breeders[len(breeders) - 1 - i])
  71. )
  72. return next_population
  73.  
  74.  
  75. # Mutation
  76.  
  77.  
  78. def mutate_population(population, chance_of_mutation):
  79. def mutate_word(word):
  80. index_modification = int(random.random() * len(word))
  81. if index_modification == 0:
  82. word = chr(97 + int(26 * random.random())) + word[1:]
  83. else:
  84. word = (
  85. word[:index_modification]
  86. + chr(97 + int(26 * random.random()))
  87. + word[index_modification + 1 :]
  88. )
  89. return word
  90.  
  91. for i in range(len(population)):
  92. if random.random() * 100 < chance_of_mutation:
  93. population[i] = mutate_word(population[i])
  94. return population
  95.  
  96.  
  97. target = "im from honduras"
  98. population_size = 300
  99. num_children = 8
  100. mutation_rate = 25
  101. population = generate_first_population(population_size, target)
  102.  
  103.  
  104. def genetic_algorithm(population, target, num_children, mutation_rate):
  105. iterations, i = 200, 0
  106. take_best, take_lucky = len(population) // 2, len(population) // 10
  107. output = [("", 0)]
  108. while target != output[0][0] and i < iterations:
  109. sorted_population = sort_population_by_fitness(population, target)
  110. breeders = select_breeders(sorted_population, take_best, take_lucky)
  111. population = create_children(breeders, num_children)
  112. population = mutate_population(population, mutation_rate)
  113. output = sort_population_by_fitness(population, target)
  114. i += 1
  115. return output[0]
  116.  
  117.  
  118. print(genetic_algorithm(population, target, num_children, mutation_rate))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement