1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 | import random POPULATION_SIZE = 4 # °³Ã¼ Áý´ÜÀÇ Å©±â MUTATION_RATE = 0.1 # µ¹¿¬ º¯ÀÌ È®·ü SIZE = 5 # ÇϳªÀÇ ¿°»öü¿¡¼ À¯ÀüÀÚ °³¼ö # ¿°»öü¸¦ Ŭ·¡½º·Î Á¤ÀÇÇÑ´Ù. class Chromosome: def __init__(self, g=[]): self.genes = g.copy() # À¯ÀüÀÚ´Â ¸®½ºÆ®·Î ±¸ÇöµÈ´Ù. self.fitness = 0 # ÀûÇÕµµ if self.genes.__len__()==0: # ¿°»öü°¡ Ãʱ⠻óÅÂÀ̸é ÃʱâÈÇÑ´Ù. i = 0 while i<SIZE: if random.random() >= 0.5: self.genes.append(1) else: self.genes.append(0) i += 1 def cal_fitness(self): # ÀûÇÕµµ¸¦ °è»êÇÑ´Ù. self.fitness = 0; value = 0 for i in range(SIZE): value += self.genes[i]*pow(2,SIZE-1-i) self.fitness = value return self.fitness def __str__(self): return self.genes.__str__() # ¿°»öü¿Í ÀûÇÕµµ¸¦ Ãâ·ÂÇÑ´Ù. def print_p(pop): i = 0 for x in pop: print("¿°»öü #", i, "=", x, "ÀûÇÕµµ=", x.cal_fitness()) i += 1 print("") # ¼±Åà ¿¬»ê def select(pop): max_value = sum([c.cal_fitness() for c in population]) pick = random.uniform(0, max_value) current = 0 # ·ê·¿ÈÙ¿¡¼ ¾î¶² Á¶°¢¿¡ ¼ÓÇÏ´ÂÁö¸¦ ¾Ë¾Æ³»´Â ·çÇÁ for c in pop: current += c.cal_fitness() if current > pick: return c # ±³Â÷ ¿¬»ê def crossover(pop): father = select(pop) mother = select(pop) index = random.randint(1, SIZE - 2) child1 = father.genes[:index] + mother.genes[index:] child2 = mother.genes[:index] + father.genes[index:] return (child1, child2) # µ¹¿¬º¯ÀÌ ¿¬»ê def mutate(c): for i in range(SIZE): if random.random() < MUTATION_RATE: if random.random() < 0.5: c.genes[i] = 1 else: c.genes[i] = 0 # ¸ÞÀÎ ÇÁ·Î±×·¥ population = [] i=0 # Ãʱ⠿°»öü¸¦ »ý¼ºÇÏ¿© °´Ã¼ Áý´Ü¿¡ Ãß°¡ÇÑ´Ù. while i<POPULATION_SIZE: population.append(Chromosome()) i += 1 count=0 population.sort(key=lambda x: x.cal_fitness(), reverse=True) print("¼¼´ë ¹øÈ£=", count) print_p(population) count=1 while population[0].cal_fitness() < 31: new_pop = [] # ¼±Åðú ±³Â÷ ¿¬»ê for _ in range(POPULATION_SIZE//2): c1, c2 = crossover(population); new_pop.append(Chromosome(c1)); new_pop.append(Chromosome(c2)); # ÀÚ½Ä ¼¼´ë°¡ ºÎ¸ð ¼¼´ë¸¦ ´ëüÇÑ´Ù. # ±íÀº º¹»ç¸¦ ¼öÇàÇÑ´Ù. population = new_pop.copy(); # µ¹¿¬º¯ÀÌ ¿¬»ê for c in population: mutate(c) # Ãâ·ÂÀ» À§ÇÑ Á¤·Ä population.sort(key=lambda x: x.cal_fitness(), reverse=True) print("¼¼´ë ¹øÈ£=", count) print_p(population) count += 1 if count > 100 : break; | cs |