python 遺傳算法求函數(shù)極值的實現(xiàn)代碼
更新時間:2020年02月11日 08:44:54 作者:zzzzjh
今天小編就為大家分享一篇python 遺傳算法求函數(shù)極值的實現(xiàn)代碼,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
廢話不多說,大家直接看代碼吧!
"""遺傳算法實現(xiàn)求函數(shù)極大值—Zjh"""
import numpy as np
import random
import matplotlib.pyplot as plt
class Ga():
"""求出二進制編碼的長度"""
def __init__(self):
self.boundsbegin = -2
self.boundsend = 3
precision = 0.0001 # 運算精確度
self.Bitlength = int(np.log2((self.boundsend - self.boundsbegin)/precision))+1#%染色體長度
self.popsize = 50# 初始種群大小
self.Generationmax = 12# 最大進化代數(shù)
self.pcrossover = 0.90# 交叉概率
self.pmutation = 0.2# 變異概率
self.population=np.random.randint(0,2,size=(self.popsize,self.Bitlength))
"""計算出適應度"""
def fitness(self,population):
Fitvalue=[]
cumsump = []
for i in population:
x=self.transform2to10(i)#二進制對應的十進制
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
"""選擇兩個基因,準備交叉"""
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
"""二進制轉換為十進制"""
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 #返回十進制的數(shù)
"""目標函數(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個個體的序號
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()
一個函數(shù)求極值的仿真的作業(yè),參考了別人的matlab代碼,用python復現(xiàn)了一遍,加深印象!
以上這篇python 遺傳算法求函數(shù)極值的實現(xiàn)代碼就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Python編程實現(xiàn)的簡單神經(jīng)網(wǎng)絡算法示例
這篇文章主要介紹了Python編程實現(xiàn)的簡單神經(jīng)網(wǎng)絡算法,結合實例形式分析了神經(jīng)網(wǎng)絡算法的原理及Python相關算法實現(xiàn)技巧,需要的朋友可以參考下2018-01-01
Python設計模式中單例模式的實現(xiàn)及在Tornado中的應用
這篇文章主要介紹了Python設計模式中單例模式的實現(xiàn)及在Tornado中的應用,講解了單例模式用于設計Tornado框架中的線程控制方面的相關問題,需要的朋友可以參考下2016-03-03
為什么入門大數(shù)據(jù)選擇Python而不是Java?
為什么入門大數(shù)據(jù)選擇Python而不是Java?這篇文章就來談談學習大數(shù)據(jù)入門語言的選擇,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-03-03
Python數(shù)據(jù)可視化教程之Matplotlib實現(xiàn)各種圖表實例
這篇文章主要給大家介紹了關于Python數(shù)據(jù)可視化教程之利用Matplotlib實現(xiàn)各種圖表的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面來一起看看吧2019-01-01
Python實現(xiàn)在線暴力破解郵箱賬號密碼功能示例【測試可用】
這篇文章主要介紹了Python實現(xiàn)在線暴力破解郵箱賬號密碼功能,結合完整實例形式分析了Python讀取txt字典文件針對郵箱的相關驗證破解操作技巧,需要的朋友可以參考下2017-09-09

