import numpy as np
import geatpy as ea
import random
pop_1=np.array([[1, 11, 21,9,16,10,8,17],
[2, 12, 22,10,17,11,9,18],
[3, 13, 23,11,18,12,10,19],
[4, 14, 24,12,19,13,11,20],
[5, 15, 25,13,20,14,12,21],
[6, 16, 26,14,21,15,13,22],
[7, 17, 27,15,22,16,14,23],
[8, 18, 28,16,23,17,15,24]])
def crossover(pop_1,pc):
j=0
while j<=3:
row_rand_array = np.arange(pop_1.shape[0])
np.random.shuffle(row_rand_array) # 现场修改序列,改变自身内容。(类似洗牌,打乱顺序)
chorm = pop_1[row_rand_array[0:2]] # 抽取pop_1中的两个个体染色体。数组
c_point1 = random.randint(0, len(chorm[0])-1)
c_point2 = random.randint(0, len(chorm[0])-1)
if c_point1 <= c_point2:
s_point = c_point1
e_point = c_point2
else:
s_point = c_point2
e_point = c_point1
print(s_point, e_point)
# r = random.random()
if 0.8 <= 0.7:
new_C = chorm
print(new_C)
else:
a = random.random()
b = random.random()
print(a, b)
chrom_n1 = chorm[0] # 父代1
chrom_n2 = chorm[1] # 父代2
print(chrom_n1,chrom_n2)
for i in range(s_point, e_point + 1): # 遍历每个交叉点
Ge1 = int(chrom_n1[i])
Ge2 = int(chrom_n2[i])
print(Ge1, Ge2)
Ge1 = Ge2 + a * (Ge1 - Ge2)
Ge2 = Ge1 + b * (Ge2 - Ge1) # 交叉后的基因
print(Ge1, Ge2)
chrom_n1[i] = Ge1
chrom_n2[i] = Ge2 # 更新染色体
# print(chorm_n1, chorm_n2)
# print(chorm_n1, chorm_n2) # 注意缩进,只要最后每个点交叉后最终的迭代结果
pop_1[row_rand_array[0:1]] = chrom_n1
pop_1[row_rand_array[1:2]] = chrom_n2 # 更新整个种群,将交叉后的染色体存入种群中
# pop_c = pop_1 # print(pop_c) #已经是更新后的种群了
j +=1
print(j)
return pop_1
dxs=crossover(pop_1,0.7)
print(dxs)
遗传算法线性交叉
猜你喜欢
转载自blog.csdn.net/huahua20190514/article/details/103186859
今日推荐
周排行