本文主要是介绍面向对象编程之Python实现遗传算法三,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
import random
import math
###########################################################################
class Point:
size=0
xmin=0.0
xmax=0.0
def __init__(self):
self.x=[]
for i in range(Point.size):
if(random.random()>0.5):
self.x.append(1)
else:
self.x.append(0)
def decode(self):
vx=0
for i in range(Point.size):
vx=vx+self.x[i]*(2**(Point.size-i-1))
vx=Point.xmin+vx*(Point.xmax-Point.xmin)/(2**Point.size-1.0)
return vx
def getFitness(self):
vy=self.decode()
y=vy*math.sin(vy*10*math.pi)+2.0
return y
def show(self):
print(self.x,self.decode(),self.getFitness())
################################################################
class Tools:
def __init__(self):
self.temp=Point()
def cross(self,a,b,ab,ba):
pos=random.randint(0,Point.size-1)
for i in range(pos):
ab.x[i]=a.x[i]
ba.x[i]=b.x[i]
for i in range(pos,Point.size-1):
ba.x[i]=a.x[i]
ab.x[i]=b.x[i]
def copy(self,a,b):
for i in range(Point.size):
b.x[i]=a.x[i]
def mutA(self,a):
pos=random.randint(0,Point.size-1)
a.x[pos]=(a.x[pos]+1)%2
def getBestPos(self,array):
pos=0
self.copy(array[pos],self.temp)
for i in range(len(array)):
if(self.temp.getFitness()<array[i].getFitness()):
self.copy(array[i],self.temp)
pos=i
return pos
def getBadPos(self,array):
pos=0
self.copy(array[pos],self.temp)
for i in range(len(array)):
if(self.temp.getFitness()>array[i].getFitness()):
self.copy(array[i],self.temp)
pos=i
return pos
#end class Tools
##########################################################################
class GA:
t=Tools()
def __init__(self,size,T):
self.size=size
self.obj=[]
self.nextobj=[]
self.sump=[]
self.temp=Point()
for i in range(self.size):
self.obj.append(Point())
self.nextobj.append(Point())
self.sump.append(0.0)
def cal(self):
sum=0
for i in range(self.size):
self.sump[i]=self.obj[i].getFitness()
sum=sum+self.sump[i]
j=0
while(j<self.size):
if(j>0):
self.sump[j]=self.sump[j]+self.sump[j-1]
j=j+1
j=0
while(j<self.size):
self.sump[j]=self.sump[j]/sum
j=j+1
def select(self):
for i in range(self.size):
if(random.random()<self.sump[i]):
pos=i
break
return pos
def doAll(self):
self.cal()
bestPos=t.getBestPos(self.obj)
t.copy(self.obj[bestPos],self.temp)
i=0
while(i<len(self.obj)/2):
m=self.select()
n=self.select()
if(random.random()<0.85):
t.cross(self.obj[m],self.obj[n],self.nextobj[2*i],self.nextobj[2*i+1])
else:
t.copy(self.obj[n],self.nextobj[2*i])
t.copy(self.obj[m],self.nextobj[2*i+1])
i=i+1
i=0
while(i<len(self.obj)):
if(random.random()>0.95):
t.mutA(self.nextobj[i])
i=i+1
badpos=t.getBadPos(self.nextobj)
t.copy(self.temp,self.nextobj[badpos])
i=0
while(i<len(self.obj)):
t.copy(self.nextobj[i],self.obj[i])
i=i+1
#end GA
Point.size=22
Point.xmax=2.0
Point.xmin=-1.0
t=Tools()
s=GA(40,t)
i=0
while(i<500):
s.doAll()
i=i+1
bestPos=t.getBestPos(s.obj)
s.obj[bestPos].show()
这篇关于面向对象编程之Python实现遗传算法三的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!