资源简介
自己对遗传算法的理解以及【Python】的实现,希望对你们有所帮助
代码片段和文件信息
import random
#初始化种群
def initialize_pop(population N V nbits):
#自变量个数V并没有用到
for i in range(N):
tempIndividual=[]
for j in nbits:
tempVal=[]
for k in range(j):
tempVal.append(random.randint(0 1))
tempIndividual.append(tempVal)
population.append(tempIndividual)
return population
import copy
import random
#轮盘赌选择法
def selection(population fitness_value N nbits):
s1 = sum(fitness_value)
temp1 = [k*1.0/s1 for k in fitness_value]
dict1 = {}
for i in range(len(population)):
dict1[i] = temp1[i]
dict2 = {}
for i in dict1:
dict2[list(dict1.keys())[list(dict1.values()).index(min(temp1))]] = min(temp1)
temp1.remove(min(temp1))
dict3 = {}
s2=0
for i in dict2:
s2 = s2 + dict2[i]
dict3[i] = s2
#采用父辈循环来选择下一代种群
temp2 = []
for i in dict3dict3dict3dict3dict3dict3:
for j in i:
r=random.random()
if r <= dict3[j]:
if len(temp2) temp2.append(j)
else:
break
temp3 = []
for i in temp2:
temp3.append(copy.deepcopy(population[i]))
population[:] = temp3
‘‘‘temp2 = []
for i in dict3:
r=random.random()
if r <= dict3[i]:
temp2.append(i)‘‘‘
#未被选择的个体重新生成
‘‘‘for i in range(N-len(temp3)):
tempIndividual=[]
for j in nbits:
tempVal=[]
for k in range(j):
评论
共有 条评论