最近接触遗传算法,参考了很多例子,有的不完全正确,边理解边修改,然后写了下面一堆传说中的狗屎。..PS1:遗传算法的原理太多了,就不细说了。CSDN很多帖子都解释的很透彻;PS2:想看简洁的直接在Youtube上搜索遗传算法,看莫麻烦的视频。别再跟代码废话了,赶紧上车,啊不,上代码。importmathimportnumpyasnpiimportmatplotlib.pyplotaspltimportrandomclassGA(object):#目标解2*sin(x)+cos(x)maximumdef__init__(self,population_size,chromosome_length,pm):self.population_size=population_sizeself.chromosome_length=chromosome_lengthself.pm=pm#初始化种群defspecies_origin(self):#生成染色体和基因population=[[]]#二维列表,包括染色体和基因foriinrange(self.population_size):temporary=[]#chromosomeregisterforjinrange(self.chromosome_length):temporary.append(random.randint(0,1))#generategene,binarypopulation.append(temporary)#addgenetochromosomereturnpopulation[1:]#返回种群,包括染色体和基因#种群解码,用于适应度判断deftranslation(self,population):#二进制转十进制chromosome_d_list=[]#创建染色体十进制列表foriinrange(len(population)):chromosome_value_d=0forjinrange(len(population[0])):chromosome_value_d+=population[i][j]*(math.pow(2,len(population[0])-j-1))chromosome_d_list.append(chromosome_value_d)returnchromosome_d_list#适应度计算deffunction(self,population,lower_bound,upper_bound):all_fitness_list=[]#创建所有染色体的适应度列表fv_list=self.translation(population)foriinrange(len(fv_list)):x=lower_bound+fv_list[i]*(upper_bound-lower_bound)/(math.pow(2,self.chromosome_length)-1)y=2*math.sin(x)+math.cos(x)#目标函数all_fitness_list.append(y)returnall_fitness_list#消除负适应度值defpositive_fitness(self,all_fitness_list):pf=[]foriinrange(len(all_fitness_list)):ifall_fitness_list[i]>0:pf.append(all_fitness_list[i])returnpf#positivefitnesschromosomelistdefpositive_chromosome(self,all_fitness_list,population):positive_chromosome_list=[]foriinrange(len(all_fitness_list)):ifall_fitness_list[i]>0:positive_chromosome_list.append(population[i])returnpositive_chromosome_list#计算正适应度之和defpf_sum(self,pf):pf_total=0foriinrange(len(pf)):pf_total+=pf[i]returnpf_total#正适应度变为小数defpf_float(self,pf_total,pf):pf_float=[]foriinrange(len(pf)):#将正适应度除以总适应度并转换为小数pf_float.append(pf[i]/pf_total)returnpf_float#累积适应度为分区准备defpf_div(self,pf_float):pft_div=[]forjinrange(len(pf_float)):#将适应度转化为轮盘概率ifj==0:pft_div.append(pf_float[j])else:pft_div.append(pf_float[j]+pft_div[j-1])returnpft_div#选择外汇佣金http://www.kaifx.cn/defselection(self,pcl,pft_div):selected_pop=[]#选择新的人口select_float=[]#Randomlygenerateddecimalsforiinrange(len(pcl)):#Generaterandomdecimalsselect_float.append(random.random())foriinrange(len(pcl)):#轮盘选择j=0whilej
