Advertisement
Guest User

python text genetic algorithm

a guest
Jan 23rd, 2019
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.87 KB | None | 0 0
  1. from datetime import datetime
  2. import random
  3. import string
  4. from tqdm import tqdm
  5.  
  6. pop_size = 512
  7. generation_count = 10000
  8. mutation_rate = 0.01
  9. alphabet = string.ascii_lowercase + " " + string.digits
  10.  
  11.  
  12. def rand_char():
  13.     return random.choice(alphabet)
  14.  
  15.  
  16. text_sequence = list(rand_char() * 100)
  17.  
  18.  
  19. class Gene:
  20.     def __init__(self):
  21.         self.text = []
  22.         self.score = 0
  23.         self.fitness = 0
  24.  
  25.     def crossover(self, other):
  26.         child1 = Gene()
  27.         child2 = Gene()
  28.         point = random.randint(0, len(text_sequence))
  29.         child1.text = self.text[:point] + other.text[point:]
  30.         child2.text = other.text[:point] + self.text[point:]
  31.  
  32.         return child1, child2
  33.  
  34.     def mutate(self):
  35.         for i in range(len(text_sequence)):
  36.             if random.random() < mutation_rate:
  37.                 self.text[i] = rand_char()
  38.  
  39.     @classmethod
  40.     def initialize(cls):
  41.         new_gene = cls()
  42.         for i in range(len(text_sequence)):
  43.             new_gene.text.append(rand_char())
  44.  
  45.         return new_gene
  46.  
  47.     def calc_score(self):
  48.         same = 0
  49.         for i in range(len(text_sequence)):
  50.             if self.text[i] == text_sequence[i]:
  51.                 same += 1
  52.  
  53.         return same
  54.  
  55.  
  56. start = datetime.now()
  57.  
  58. pop = []
  59.  
  60. for i in range(pop_size):
  61.     pop.append(Gene.initialize())
  62.  
  63. top_gene = Gene()
  64. with tqdm(total=generation_count, disable=False) as t:
  65.     while top_gene.score != len(text_sequence):  # each generation
  66.         t.set_postfix(str="score:{}/{}".format(str(top_gene.score), str(len(text_sequence))))
  67.         t.update()
  68.  
  69.         score_sum = 0
  70.         for gene in pop:  # each gene
  71.             gene.score = gene.calc_score()
  72.             score_sum += gene.score
  73.  
  74.         top_gene = pop[0]
  75.         for gene in pop:  # calc fitness
  76.             gene.fitness = gene.score / score_sum
  77.             if gene.fitness > top_gene.fitness:
  78.                 top_gene = gene
  79.  
  80.         new_pop = []
  81.         for k in range(int(len(pop) / 2)):  # each gene
  82.             childs = random.choices(population=pop, k=4)
  83.             child1 = max(childs[:2], key=lambda x: x.fitness)
  84.             child2 = max(childs[2:], key=lambda x: x.fitness)
  85.             # for i in range(2):  # 2 times
  86.             #     rand = random.random()
  87.             #     sum_up = 0
  88.             #     for j in range(pop_size):
  89.             #         sum_up += pop[j].fitness
  90.             #         if sum_up > rand:
  91.             #             childs.append(pop[j])
  92.             #             break
  93.             child1, child2 = child1.crossover(child2)
  94.             child1.mutate()
  95.             child2.mutate()
  96.             new_pop.append(child1)
  97.             new_pop.append(child2)
  98.  
  99.         pop[random.randint(0, len(pop) - 1)] = top_gene
  100.         pop = new_pop
  101.  
  102. end = datetime.now()
  103. print("{}".format(str((end - start).total_seconds() * 1000)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement