python 遺傳算法求函數(shù)極值的實(shí)現(xiàn)代碼
廢話不多說(shuō),大家直接看代碼吧!
"""遺傳算法實(shí)現(xiàn)求函數(shù)極大值—Zjh""" import numpy as np import random import matplotlib.pyplot as plt class Ga(): """求出二進(jìn)制編碼的長(zhǎng)度""" def __init__(self): self.boundsbegin = -2 self.boundsend = 3 precision = 0.0001 # 運(yùn)算精確度 self.Bitlength = int(np.log2((self.boundsend - self.boundsbegin)/precision))+1#%染色體長(zhǎng)度 self.popsize = 50# 初始種群大小 self.Generationmax = 12# 最大進(jìn)化代數(shù) self.pcrossover = 0.90# 交叉概率 self.pmutation = 0.2# 變異概率 self.population=np.random.randint(0,2,size=(self.popsize,self.Bitlength)) """計(jì)算出適應(yīng)度""" def fitness(self,population): Fitvalue=[] cumsump = [] for i in population: x=self.transform2to10(i)#二進(jìn)制對(duì)應(yīng)的十進(jìn)制 xx=self.boundsbegin + x * (self.boundsend - self.boundsbegin) / (pow(2,self.Bitlength)-1) s=self.targetfun(xx) Fitvalue.append(s) fsum=sum(Fitvalue) everypopulation=[x/fsum for x in Fitvalue] cumsump.append(everypopulation[0]) everypopulation.remove(everypopulation[0]) for j in everypopulation: p=cumsump[-1]+j cumsump.append(p) return Fitvalue,cumsump """選擇兩個(gè)基因,準(zhǔn)備交叉""" def select(self,cumsump): seln=[] for i in range(2): j = 1 r=np.random.uniform(0,1) prand =[x-r for x in cumsump] while prand[j] < 0: j = j + 1 seln.append(j) return seln """交叉""" def crossover(self, seln, pc): d=self.population[seln[1]].copy() f=self.population[seln[0]].copy() r=np.random.uniform() if r<pc: print('yes') c=np.random.randint(1,self.Bitlength-1) print(c) a=self.population[seln[1]][c:] b=self.population[seln[0]][c:] d[c:]=b f[c:]=a print(d) print(f) g=d h=f else: g=self.population[seln[1]] h=self.population[seln[0]] return g,h """變異操作""" def mutation(self,scnew,pmutation): r=np.random.uniform(0, 1) if r < pmutation: v=np.random.randint(0,self.Bitlength) scnew[v]=abs(scnew[v]-1) else: scnew=scnew return scnew """二進(jìn)制轉(zhuǎn)換為十進(jìn)制""" def transform2to10(self,population): #x=population[-1] #最后一位的值 x=0 #n=len(population) n=self.Bitlength p=population.copy() p=p.tolist() p.reverse() for j in range(n): x=x+p[j]*pow(2,j) return x #返回十進(jìn)制的數(shù) """目標(biāo)函數(shù)""" def targetfun(self,x): #y = x∗(np.sin(10∗(np.pi)∗x))+ 2 y=x*(np.sin(10*np.pi*x))+2 return y if __name__ == '__main__': Generationmax=12 gg=Ga() scnew=[] ymax=[] #print(gg.population) Fitvalue, cumsump=gg.fitness(gg.population) Generation = 1 while Generation < Generationmax +1: Fitvalue, cumsump = gg.fitness(gg.population) for j in range(0,gg.popsize,2): seln = gg.select( cumsump) #返回選中的2個(gè)個(gè)體的序號(hào) scro = gg.crossover(seln, gg.pcrossover) #返回兩條染色體 s1=gg.mutation(scro[0],gg.pmutation) s2=gg.mutation(scro[1],gg.pmutation) scnew.append(s1) scnew.append(s2) gg.population = scnew Fitvalue, cumsump = gg.fitness(gg.population) fmax=max(Fitvalue) d=Fitvalue.index(fmax) ymax.append(fmax) x = gg.transform2to10(gg.population[d]) xx = gg.boundsbegin + x * (gg.boundsend - gg.boundsbegin) / (pow(2, gg.Bitlength) - 1) Generation = Generation + 1 Bestpopulation = xx Targetmax = gg.targetfun(xx) print(xx) print(Targetmax) x=np.linspace(-2,3,30) y=x*(np.sin(10*np.pi*x))+2 plt.scatter(2.65,4.65,c='red') plt.xlim(0,5) plt.ylim(0,6) plt.plot(x,y) plt.annotate('local max', xy=(2.7,4.8), xytext=(3.6, 5.2),arrowprops=dict(facecolor='black', shrink=0.05)) plt.show()
一個(gè)函數(shù)求極值的仿真的作業(yè),參考了別人的matlab代碼,用python復(fù)現(xiàn)了一遍,加深印象!
以上這篇python 遺傳算法求函數(shù)極值的實(shí)現(xiàn)代碼就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python實(shí)現(xiàn)的十進(jìn)制小數(shù)與二進(jìn)制小數(shù)相互轉(zhuǎn)換功能
這篇文章主要介紹了Python實(shí)現(xiàn)的十進(jìn)制小數(shù)與二進(jìn)制小數(shù)相互轉(zhuǎn)換功能,結(jié)合具體實(shí)例形式詳細(xì)分析了二進(jìn)制與十進(jìn)制相互轉(zhuǎn)換的原理及Python相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2017-10-10OpenCV-Python使用分水嶺算法實(shí)現(xiàn)圖像的分割與提取
在圖像的處理過(guò)程中,經(jīng)常需要從圖像中將前景對(duì)象作為目標(biāo)圖像分割或者提取出來(lái)。本文就介紹了使用分水嶺算法實(shí)現(xiàn)圖像的分割與提取,感興趣的可以了解一下2021-06-06python爬蟲(chóng)之爬取谷歌趨勢(shì)數(shù)據(jù)
這篇文章主要介紹了python爬蟲(chóng)之爬取谷歌趨勢(shì)數(shù)據(jù),文中有非常詳細(xì)的代碼示例,對(duì)正在學(xué)習(xí)python爬蟲(chóng)的小伙伴們有非常好的幫助,需要的朋友可以參考下2021-04-0420行python代碼實(shí)現(xiàn)人臉識(shí)別
這篇文章主要介紹了python人臉識(shí)別,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-05-05Python 內(nèi)置函數(shù)進(jìn)制轉(zhuǎn)換的用法(十進(jìn)制轉(zhuǎn)二進(jìn)制、八進(jìn)制、十六進(jìn)制)
這篇文章主要介紹了使用Python內(nèi)置函數(shù):bin()、oct()、int()、hex()可實(shí)現(xiàn)進(jìn)制轉(zhuǎn)換的一些用法,需要的朋友可以參考下2018-04-04Python多線程threading模塊用法實(shí)例分析
這篇文章主要介紹了Python多線程threading模塊用法,結(jié)合實(shí)例形式分析了Python多線程threading模塊原理、功能、常見(jiàn)應(yīng)用及相關(guān)操作注意事項(xiàng),需要的朋友可以參考下2019-05-05pandas基于時(shí)間序列的固定時(shí)間間隔求均值的方法
今天小編就為大家分享一篇pandas基于時(shí)間序列的固定時(shí)間間隔求均值的方法,具有好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-07-07Python中Selenium對(duì)Cookie的操作方法
Cookie內(nèi)記錄用戶名和密碼(加密)信息,只要請(qǐng)求時(shí)服務(wù)器收到Cookie,識(shí)別成功,默認(rèn)為已登陸,今天通過(guò)本文給大家分享Selenium對(duì)Cookie的操作方法,感興趣的朋友一起看看吧2021-07-07對(duì)Python _取log的幾種方式小結(jié)
今天小編就為大家分享一篇對(duì)Python _取log的幾種方式小結(jié),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-07-07