python 遗传算法求函数极值的实现代码遗传算法求函数极值的实现代码
今天小编就为大家分享一篇python 遗传算法求函数极值的实现代码,具有很好的参考价值,希望对大家有所帮
助。一起跟随小编过来看看吧
废话不多说,大家直接看代码吧!
"""遗传算法实现求函数极大值—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# 最大进化代数
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)
评论0