遗传算法线性交叉,多维数组抽取

import numpy as np
import random
import geatpy as ea

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]])
# print(pop_1.shape[1])  # 行抽取,有多少行,结果为8.若改为pop_1.shape[1],则为有多少列,结果为3
row_rand_array = np.arange(pop_1.shape[0])
# print(row_rand_array) #[0 1 2 3 4 5 6 7]
np.random.shuffle(row_rand_array)  # 现场修改序列,改变自身内容。(类似洗牌,打乱顺序)
# print(row_rand_array)  # 将row_rand_array打乱顺序,覆盖原来的row_rand_array,[1 7 5 3 4 2 0 6]
chorm = pop_1[row_rand_array[0:2]]  # 抽取pop_1中第1个和第3个个体染色体。
print(chorm)  # [[ 2 12 22 10 17 11  9 18][ 8 18 28 16 23 17 15 24]]
# print(len(chorm[0]))  #

# chorm=np.array([[1, 11, 21,9,16,10,8,17],
#                   [2, 12, 22,10,17,11,9,18]])
c_point1 = random.randint(0,len(chorm[0])-1)
c_point2 = random.randint(0, len(chorm[0])-1)  # 随机生成交叉起终点
print(c_point1,c_point2)
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)
    chorm_n1=chorm[0]  #父代1
    chorm_n2=chorm[1]  #父代2
    for i in range(s_point, e_point + 1):  #遍历每个交叉点
        Ge1 = int(chorm_n1[i])
        Ge2 = int(chorm_n2[i])
        print(Ge1,Ge2)
        Ge1 = Ge2 + a * (Ge1 - Ge2)
        Ge2 = Ge1 + b * (Ge2 - Ge1)  # 交叉后的基因
        print(Ge1,Ge2)
        chorm_n1[i] = Ge1
        chorm_n2[i] = Ge2
        # print(chorm_n1, chorm_n2)  # 这种缩进显示每一次迭代的结果
    print(chorm_n1, chorm_n2)  # 注意缩进,只要最后每个点交叉后最终的迭代结果
    pop_1[row_rand_array[0:1]]=chorm_n1
    pop_1[row_rand_array[1:2]] = chorm_n2  #更新整个种群,将交叉后的染色体存入种群中
    print(pop_1)
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值