遗传算法 学习笔记

(原文曾在:http://liyitan.sinaapp.com 都是本人)

最近听大牛讨论遗传算法,讨论其对各种启发搜索问题,都有比较好的鲁棒性,所以心痒+手贱,尝试了一下。

实际上仅仅只实现了,搜索一个字符串(有数字组成)的功能。Python代码如下(比较水):

话所,速度果然还真够慢的······

输入:一个字符串(从data.txt文件读入),作为搜索目标

输出:每50次繁殖,显示一个种群中的最优解(就是距离)

注释:当然,这个问题本身自然不需要使用遗传算法,我只是写着玩

View Code
import matplotlib.pyplot as plt
import numpy as np
import copy

def similar(x,y):
sum = 0
# print x,y
for i,elem in enumerate(x):
sum += np.abs(elem-y[i])
return sum

class gene:
def __init__(self,data):
self.data = data
def sortkey(self,x):
return similar(self.data,x)
def select(self,Mlist,M):
p = []
for elem in Mlist:
#the function which will effect the dztion
p.append(float(1)/(1+similar(self.data,elem)))
mu = np.sum(p)
p = [elem/float(mu) for elem in p]
newMlist = []
se = -1
while len(newMlist) < M:
you = np.random.rand()
for i,elem in enumerate(p):
you -= elem
if you < 0:
se = i
break
newMlist.append(Mlist[se])
return newMlist
def min(a,b):
if a<0 or b < 0:
raise Exception('cccc')
if a < b:
return a
return b
def geneNum(self,M,pb,pj):
Mlist = []
for i in range(M):
temp = []
for j in range(len(self.data)):
temp.append(int(np.random.rand()*10))
Mlist.append(temp)
count = 0
while True:
newMlist = []
Mlist.sort(key = self.sortkey)
# print 'sort'
if count >= 1000 or similar(Mlist[0],self.data) == 0:
print '%d:' % count +str(Mlist[0])
break
if count%50 == 0:
print '%d:' % count +str(Mlist[0])
# for i in range(M):
newMlist = self.select(Mlist,M)
# newMlist.append(Mlist[i])
for i in range(int(M*pb)):
temp = copy.copy(Mlist[int(np.random.rand()*len(Mlist))])
chg = int(np.random.rand()*10)
pos = int(np.random.rand()*len(self.data))
temp[pos] = chg
newMlist.append(temp)
# print count
#
print 'b:'+str(newMlist)
for i in range(int(M*pj)):
a = int(np.random.rand()*len(Mlist))
b = int(np.random.rand()*len(Mlist))
pos1 = int(np.random.rand()*len(self.data))
pos2 = int(np.random.rand()*len(self.data))
length = int(np.random.rand()*min(len(self.data)-pos1-1,len(self.data)-pos2-1))
temp = Mlist[a][:pos1]
temp.extend(Mlist[b][pos2:pos2+length])
temp.extend(Mlist[a][pos1+length:])
newMlist.append(temp)
temp = Mlist[b][:pos2]
temp.extend(Mlist[a][pos1:pos1+length])
temp.extend(Mlist[b][pos2+length:])
newMlist.append(temp)
# print 'j:'+str(newMlist)
Mlist = newMlist
# print newMlist
count += 1
def main():
with open('data.txt','rb') as f:
sp = f.readline().split()
data = []
for c in sp[0]:
data.append(int(c))
g = gene(data)
g.geneNum(100,0.1,0.7)

if __name__ == '__main__':
main()


posted on 2012-03-04 15:33  liyitan  阅读(487)  评论(1编辑  收藏  举报

导航