我目前正在开展一个学校项目,该项目包括在给定孔隙率的情况下从多孔介质中找到最大的水(因此我们找到了最佳的孔隙分布)。我使用遗传算法通过将介质建模为方形矩阵来解决这个问题,其中 0 表示空隙,1 表示固体介质,2 表示水。我在互联网上查找交叉率、突变率等的最佳值。问题是有时我达到最大值,然后它开始在几代人中下降,有时我在所有几代人的培养基中都被 0 水困住。我不知道我哪里出错了。如果您需要进化过程或交叉的代码,请随时在评论中告诉我。提前致谢。
交叉:此功能交叉两种介质并保持孔隙率,孩子应与父母双方具有相同的孔隙率。
def crossover(g,h,n,p,cp):#crossover(parent1,parent2,size of matrix, porosity,crossover rate)
b=n*n
k=int(b*p)
l=g
if cp>rnd.random():
l[n//3:2*n//3] = h[n//3:2*n//3]
count = 0
for i in range(n):
for j in range(n):
if l[i][j] == 1:
count +=1
diff = count-k
if diff>0:
while diff>0:
i=rnd.randint(0,n-1)
j=rnd.randint(0,n-1)
if l[i][j] == 1:
l[i][j] = 0
diff -=1
if diff<0:
while diff<0:
i=rnd.randint(0,n-1)
j=rnd.randint(0,n-1)
if l[i][j] == 0:
l[i][j] = 1
diff+=1
return l
该交叉是两点交叉。
进化代码:
def evolve(pop,m,n,p,mp,cp,sp=0.3):#evolve(the population list,population length, matrix size,porosity,mutation probability, crossover probability, rate of individuals to be selected for the upcoming generation)
graded = [ (ratio(pop[i], n), i) for i in range(m)]
graded = [ x[1] for x in sorted(graded)]
retain_length = int(m*sp)
parents = [pop[x] for x in graded[retain_length:]]
# randomly add other individuals to promote genetic diversity
for individual in graded[:retain_length]:
if 0.025 > rnd.random():
parents.append(pop[individual])
# mutate some individuals
for individual in parents:
if mp>rnd.random():
individual = mutate(individual,n,mp)
# crossover parents to create children
parents_length = len(parents)
desired_length = m - parents_length
children = []
while len(children) < desired_length:
male = rnd.randint(0, parents_length-1)
female = rnd.randint(0, parents_length-1)
if male != female:
male = parents[male]
female = parents[female]
children.append(crossover(male,female,n,p,cp))
parents.extend(children)
return parents
编辑:将突变率提高到 0.05 后,遗传算法给了我很好的结果,但这是否意味着我失去了一些父母基因?另一个问题,如果我选择人口作为第一次 GA 运行的结果并在下一次运行中使用它,它会提高性能吗?