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 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
| import math import random import time,os from matplotlib.pyplot import * import numpy as np
class Evolution(): def __init__(self, population, mutation_rate, add, retain_rate, data): self.num = population self.mutation_rate = mutation_rate self.add = add self.retain_rate = retain_rate self.best = [[1,2],float("inf")] self.data = data self.mutationnum = 0 self.insert = range(0, len(self.data)) self.AllMaxy = [] self.d = 0 self.population = self.Gene_population() matplotlib.use('Agg') def Gene_population(self): """ 获取初始种群(一个含有 self.num 个长度为 self.chromosome_size 的染色体的列表) """ x = [] newx = range(0, len(self.data)) while len(x) < self.num: if newx not in x: x += [newx[:]] random.shuffle(newx) return x[:] def Evolve(self): """ 进化 对当前一代种群依次进行选择、交叉并生成新一代种群,然后对新一代种群进行变异 """ self.Selection() result = '目前第 ' + str(self.d) + ' 代, 此代最优为 ' + str(1 / self.Fitness(self.population[0])) + ' , 变异次数为 ' + str(self.mutationnum) self.Crossover() self.Force_Insert() self.Mutation()
self.d += 1 return result def Fitness(self, xi): """ 计算适应度,将染色体解码为定义域之间的数字,代入函数计算 因为是求最大值,所以数值越大,适应度越高 """ start = 0 distance = 0.0 for end in range(1, len(xi)): distance += ((self.data[xi[start]][1][0] * 1.0 - self.data[xi[end]][1][0]) ** 2 + (self.data[xi[start]][1][1] * 1.0 - self.data[xi[end]][1][1]) ** 2) ** 0.5 start = end return 1 / distance
def Selection(self): """ 选择 先对适应度从大到小排序,选出存活的染色体 再进行随机选择,选出适应度虽然小,但是幸存下来的个体 """ xy = sorted([(i, j) for i, j in [(self.Fitness(xi), xi) for xi in self.population]], reverse = True) x = [x1 for y1, x1 in xy] y = [y1 for y1, x1 in xy]
eMaxy = 1 / y[0] self.AllMaxy += [eMaxy] self.population = x[:int(self.num * self.retain_rate)]
if eMaxy < self.best[1]: self.PlotAndSave(x[0], y[0], 1) os.system('cls') print x[0], '\n', '最佳第', self.d, '代', '最优路径长度为', eMaxy self.best = [x[0][:],eMaxy] def Crossover(self): """ 染色体的交叉、繁殖,生成新一代的种群 新出生的孩子,最终会被加入存活下来的父母之中,形成新一代的种群。 """ length = len(self.population) for i in range(length): father= random.choice(self.population) mother = random.choice(self.population) r1 = np.random.random_integers(0, len(father) - 1) r2 = np.random.random_integers(1, len(mother) - r1)
DNA1 = father[r1:r1 + r2] DNA2 = [] for i in range(len(mother)): if mother[i] not in DNA1: DNA2 += [mother[i]] child = [] for i in range(r1): child += [DNA2[i]]
child += DNA1 + DNA2[r1:]
self.population += [child[:]]
def Force_Insert(self): while len(self.population) < self.num: self.population += [self.insert[:]] random.shuffle(self.insert)
def Mutation(self): """ 变异 对种群中的所有个体,随机改变某个个体中的某个基因 """ each_mutation_rate = self.mutation_rate for i in range(len(self.population)): if random.uniform(0,1) < each_mutation_rate: r = np.random.randint(0, len(self.population[i])) self.population[i][r], self.population[i][len(self.population[i]) - r - 1] = self.population[i][len(self.population[i]) - r - 1], self.population[i][r] self.mutationnum += 1 each_mutation_rate += self.add
def PlotAndSave(self, x, y, f):
plot(range(1, len(self.AllMaxy) + 1), self.AllMaxy, 'b') title(str(x) + '\n\n' + str(1 / y), fontsize = 7) if f: savefig('Max.jpg') else: savefig('%d_Max.jpg' %self.d) close('all')
xr = [] yr = [] for i in x: xr += [self.data[i][1][0]] yr += [self.data[i][1][1]]
xr = np.array(xr + [xr[0]]) yr = np.array(yr + [yr[0]]) x0 = xr[:2] y0 = yr[:2] xr = xr[1:] yr = yr[1:] quiver(x0[:-1], y0[:-1], x0[1:] - x0[:-1], y0[1:] - y0[:-1], scale_units = 'xy', angles = 'xy', scale = 1, color='r') quiver(xr[:-1], yr[:-1], xr[1:] - xr[:-1], yr[1:] - yr[:-1], scale_units = 'xy', angles = 'xy', scale = 1) if f: savefig('Max_Road.jpg') else: savefig('%d_Road.jpg' %self.d) close('all')
time.clock()
population = 1000 mutation_rate = 0.001 add = 0.05 retain_rate = 0.5 data = [["*", [37, 52]], ["*", [49, 49]], ... ,["*", [30,40]]]
gene = Evolution(population, mutation_rate, add, retain_rate, data) while 1: t = time.clock() minute, second = divmod(t, 60) hour, minute = divmod(minute, 60) try: print '\r', gene.Evolve(), " 花费时间 %02d:%02d:%02d" %(hour, minute, second), except: gene.PlotAndSave(gene.population[:][0], gene.Fitness(gene.population[0]), 0)
|