defget_population(self, length, count): # get a list of count numbers chromosome (length : length) return [self.get_chromosome(length) for i inrange(count)]
defget_chromosome(self, length): # 随机生成染色体变量 # a bit ( 0, 1 ) represent a gene chromosome = 0 for i inrange(length): chromosome |= ( 1 << i ) * random.randint(0, 1) print(chromosome) print(chromosome * 9.0/ (2**(self.length)-1)) return chromosome
deffitness(self, chromosome): # 解码和适应性函数 x = self.decode(chromosome) return2 * math.sin( 2 * x ) + math.cos( 3 * x )
defselection(self, retain_rate, random_select_rate): # 通过适应度大小从大到小进行排序,最后生成的仍然是二进制的列表 graded = [(self.fitness(chromosome), chromosome) for chromosome in self.population] graded = [x[1] for x insorted(graded, reverse=True)]
# 从剩余的80%里面选出适应性不强,但是幸存的染色体(概率0.5) for chromosome in graded[retain_length:]: if random.random() < random_select_rate: parents.append(chromosome) return parents
defresult(self): # 获得当前最优的个体值 graded = [(self.fitness(chromosome), chromosome) for chromosome in self.population] graded = [ x[1] for x insorted(graded, reverse = True)] X1 = [i / float(10) for i inrange(0, 100, 1)] Y1 = [2 * math.sin( 2 * x ) + math.cos( 3 * x ) for x in X1] plt.plot(X1, Y1) plt.show() return ga.decode(graded[0])
if __name__ == '__main__': # 染色体长度为17,群落数量是300 ga = GA(17, 300) for x inrange(200): ga.evolve() print('x = %f' %(ga.result()))