我正在尝试使用numpy对遗传算法种群进行交叉。 我已使用父级1和父级2分割了人口。
population = np.random.randint(2, size=(4,8))
p1 = population[::2]
p2 = population[1::2]
但是我无法找出任何lambda或numpy命令对父母进行多点交叉。
该概念是将ith row of p1
并与ith row of p2
随机交换一些位。
答案 0 :(得分:0)
我认为您想从p1和p2中随机选择,逐个单元地选择。
为了更容易理解,我将p1更改为10到15,将p2更改为20到25。在这些范围内随机生成p1和p2。
p1
Out[66]:
array([[15, 15, 13, 14, 12, 13, 12, 12],
[14, 11, 11, 10, 12, 12, 10, 12],
[12, 11, 14, 15, 14, 10, 13, 10],
[11, 12, 10, 13, 14, 13, 12, 13]])
In [67]: p2
Out[67]:
array([[23, 25, 24, 21, 24, 20, 24, 25],
[21, 21, 20, 20, 25, 22, 24, 22],
[24, 22, 25, 20, 21, 22, 21, 22],
[22, 20, 21, 22, 25, 23, 22, 21]])
In [68]: sieve=np.random.randint(2, size=(4,8))
In [69]: sieve
Out[69]:
array([[0, 1, 0, 1, 1, 0, 1, 0],
[1, 1, 1, 0, 0, 1, 1, 1],
[0, 1, 1, 0, 0, 1, 1, 0],
[0, 0, 0, 1, 1, 1, 1, 1]])
In [70]: not_sieve=sieve^1 # Complement of sieve
In [71]: pn = p1*sieve + p2*not_sieve
In [72]: pn
Out[72]:
array([[23, 15, 24, 14, 12, 20, 12, 25],
[14, 11, 11, 20, 25, 12, 10, 12],
[24, 11, 14, 20, 21, 10, 13, 22],
[22, 20, 21, 13, 14, 13, 12, 13]])
当筛子为1时,青少年中的数字来自p1 筛子为0时,二十年代的数字来自p2
也许可以提高效率,但这是您期望的输出结果吗?