遗传算法求二元函数极值怎么编码_遗传算法求解一元函数二元函数最值
##——————————————————————————施工中————————————————————————————##
import random
import math
import numpy
#于2020.10.16日寫,本程序為老師布置的遺傳算法的練習#design by zqh#聯(lián)系方式QQ962903415,博客園-https://www.cnblogs.com/zqh962903415
#——————————————參數(shù)部分————————————————#
mainui='''
design by zqh
遺傳算法求解函數(shù)在實數(shù)域的最小值
選擇函數(shù)的類型
1.一元函數(shù)
2.二元函數(shù)
3.更改種群規(guī)模和迭代世代數(shù)
種群規(guī)模默認15,世代數(shù)100
'''
firstui='''
design by zqh
請輸入初代自變量的區(qū)間(請輸入正數(shù)或者負數(shù))
本區(qū)間選的離最優(yōu)值越接近
得到最優(yōu)值的速度越快越準確
'''
secondui='''
___請輸入公式___
注意:自變量用i表示
注意:乘號用*表示,加號用+表示,減號用-表示
注意:sin函數(shù)用math.sin()表示,cos函數(shù)用math.cos()表示
注意:e用exp()表示
注意:ln(10)用math.log(10,math.e)表示
'''
secondui2='''
___請輸入公式___
自變量用x和y表示
注意:乘號用*表示,加號用+表示,減號用-表示
注意:sin函數(shù)用math.sin()表示,cos函數(shù)用math.cos()表示
注意:e用math.exp()表示
注意:ln(10)用math.log(10,math.e)表示
'''
populationsize=14 #種群尺寸
popgeneration=100 #程序執(zhí)行的世代數(shù)
basedig=[] #存放每代的最優(yōu)良的那一個單體,用于制圖
fitvalue=[] #存放每代的最優(yōu)良的單體的適應度值,用于制圖
#——————————————(產(chǎn)生種群)的模塊————————————————#
def createPop(popsize):
ret=[]
for i in range(0,popsize):
num=round(random.uniform(int(sectionleft), int(sectionright)),3)
ret.append(num)
return ret
def createPop2(popsize):
ret=[]
for i in range(0,popsize):
num=round(random.uniform(int(xsectionleft), int(xsectionright)),3)
ret.append(num)
return ret
def createPop3(popsize):
ret=[]
for i in range(0,popsize):
num=round(random.uniform(int(ysectionleft), int(ysectionright)),3)
ret.append(num)
return ret
#——————————————交叉的模塊————————————————#
def crossOver(population):
ret=[]
for i in range(0,len(population)):
target=0
x1=round(random.choice(population),3)
# while target!=1:
x2=round(random.choice(population),3)
# if x2!=x1:
# target=1
# if x2==x1:
# continue
ret.append(round((x1+x2)/2,3))
# print('隨機選兩個%s和%s,求和除以2后%s' %(x1,x2,round((x1+x2)/2,3)))
return ret
#——————————————變異的模塊————————————————#
def mutation(population):
newpop=[]
expect=0
for i in population:
expect=expect+i
expect=round(expect/len(population),3)
# print('求得數(shù)學期望',expect)
for i1 in population:
vari=random.uniform(expect-3,expect+3)
# print('從(miu-3sigma),(miu+3sigma)取任意自變量',vari)
switch=random.choice(['a','b'])
if switch=='a':
nor_distru = (1 / pow(2 * math.pi, 1 / 2)) * math.exp(-1*pow((vari-expect),2)/2)
if switch=='b':
nor_distru =-1* (1 / pow(2 * math.pi, 1 / 2)) * math.exp(-1 * pow((vari - expect), 2) / 2)
# print('自變量帶入高斯分布函數(shù)得到擾動',nor_distru)
count=i1+nor_distru
newpop.append(round(count,3))
# print('高斯擾動后的(變異)新種群',newpop)
return newpop
#——————————————自寫的排序公式————————————————#
# def paixu(poplist):
# ret=[]
# while(poplist !=[]):
# minkey=poplist[0]
# for i in poplist:
# if minkey>i:
# minkey=i
# if minkey
# minkey=minkey
# ret.append(minkey)
# position=poplist.index(minkey)
# del poplist[position]
# return ret
#——————————————選擇函數(shù)的公式————————————————#
def fx(poplist,gongshi):
ret = []
for i in poplist:
res = eval(gongshi)
ret.append(round(res,5))
return ret
def fx2(poplist,poplist2,gongshi):
xkey = []
ykey=[]
final=[]
ret=[]
for x in poplist:
for y in poplist2:
res = eval(gongshi)
xkey.append(x)
ykey.append(y)
final.append(round(res,5))
ret.append(xkey)
ret.append(ykey)
ret.append(final)
return ret
#——————————————適應度選擇函數(shù)————————————————#
def popChoice(population):
dict1={}
ret1=[]
ret=[]
popfit=[]
unionpop=list(set(a).union(set(population)))
# print('新老種群并集',unionpop)
popfit=fx(unionpop,gongshi)
# print('將并集求適應度函數(shù)值',popfit)
for xp in range(0,len(unionpop)):
dict1.update({popfit[xp]:unionpop[xp]})
print(dict1)
popfit.sort()
unionpop =popfit
# print('將其從小到大排列',unionpop)
for i1 in range(len(population)):
ret1.append(unionpop[i1])
# print('只取前面popsize個',ret1)
for xp1 in ret1:
ret.append(dict1[xp1])
print('新種群',ret)
print('本代最優(yōu)單體為%s,它的適應度為%s' %(ret[0],ret1[0]))
print('#------結果——————#')
print('最小值處的自變量為%s,取得fx的最小值為%s' % (ret[0],ret1[0]))
print('#------結果——————#')
fitvalue.append(ret1[0])
basedig.append(ret[0])
return ret
def popChoice2(population,population2):
dict1={}
xpop=[]
ypop=[]
ret1=[]
ret=[]
popfit=[]
unionpop=list(set(a).union(set(population)))
# print('新老種群并集',unionpop)
unionpop2=list(set(a1).union(set(population2)))
# print('新老種群并集',unionpop2)
popfit=fx2(unionpop,unionpop2,gongshi)
# print('將并集求適應度函數(shù)值',popfit[2])
for xp in range(0, len(popfit[2])):
dict1.update({popfit[2][xp]: [popfit[0][xp],popfit[1][xp]]})
print(dict1)
popfit=popfit[2]
popfit.sort()
unionpop =popfit
# print('將其適應度函數(shù)值從小到大排列',unionpop)
for i1 in range(len(population)):
ret1.append(unionpop[i1])
# print('只取前面popsize個',ret1)
for xp1 in ret1:
ret.append(dict1[xp1])
xpop.append(dict1[xp1][0])
ypop.append(dict1[xp1][1])
print('新種群',ret)
print('本代最優(yōu)單體為%s,它的適應度為%s' %(ret[0],ret1[0]))
print('#------結果——————#')
print('最小值處的自變量為%s,取得fx的最小值為%s' % (ret[0],ret1[0]))
print('#------結果——————#')
ret.clear()
ret.append(xpop)
ret.append(ypop)
return ret
#——————————————函數(shù)主體————————————————#
while 1:
print(mainui)
xuhao=input('請輸入操作序號并按下回車')
try:
if xuhao=='1':
print(firstui)
sectionleft=input('初代區(qū)間左端>>>>')
sectionright=input('初代區(qū)間右端>>>>')
print(secondui)
gongshi=input('>>>>')
start=createPop(populationsize)
print('初始種群', start)
a = start
for i in range(0,popgeneration):
b=crossOver(a)
print('交叉后的新種群',b)
c=mutation(b)
print('變異后的新種群',c)
d=popChoice(c)
a=d
if xuhao=='2':
print(firstui)
xsectionleft=input('x初代區(qū)間左端>>>>')
xsectionright=input('x初代區(qū)間右端>>>>')
ysectionleft=input('y初代區(qū)間左端>>>>')
ysectionright=input('y初代區(qū)間右端>>>>')
print(secondui2)
gongshi=input('>>>>')
start=createPop2(populationsize)
print('初始種群', start)
a = start
start1=createPop3(populationsize)
print('初始種群', start1)
a1= start1
for i in range(0,popgeneration):
c=mutation(a)
c1=mutation(a1)
print('變異后的新種群',c)
print('變異后的新種群',c1)
d=popChoice2(c,c1)
a=d[0]
a1=d[1]
if xuhao == '3':
tp1 = input('請輸入種群尺寸') # 種群尺寸
tp2 = input('請輸入世代數(shù)') # 程序執(zhí)行的世代數(shù)
if tp1.isdigit()==False or tp2.isdigit()==False:
print('種群尺寸和世代數(shù)只能輸入數(shù)字')
else:
populationsize =int(tp1) # 種群尺寸
popgeneration =int(tp2) # 程序執(zhí)行的世代數(shù)
except Exception as wrong:
print('操作有誤,程序重啟')
# plt.plot(basedig,fitvalue)
# plt.ylabel('fitness value') #為y軸加注釋
# plt.xlabel('best one') #為x軸加注釋
# plt.show()
#于2020.10.16日寫,本程序為老師布置的遺傳算法的練習
# #design by zqh#聯(lián)系方式QQ962903415,博客園-https://www.cnblogs.com/zqh962903415
總結
以上是生活随笔為你收集整理的遗传算法求二元函数极值怎么编码_遗传算法求解一元函数二元函数最值的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: layui table勾选框的修改_la
- 下一篇: python模块搜索原则_详解pytho