我的 GA 中的交叉算法与您使用的不同——不是更好,只是不同。总之,我将 crossover 编码为数组拼接/连接操作,而不是替换,其中拼接点是随机的(并且也是“同步的”,因此当两个拼接点部分被组装成与每个父级相同长度的子向量。
我觉得用代码解释起来要容易得多:
DOMAIN_LENGTH = 14
def crossover(v1, v2):
crossover_point = random.randint(1, DOMAIN_LENGTH-2)
return v1[:crossover_point] + v2[crossover_point:]
# create a simple function to generate a couple of 'parent' vectors
>>> fnx = lambda v : [random.choice(range(10)) for c in range(DOMAIN_LENGTH)]
# now generate those parent vectors
>>> v1 = fnx(DOMAIN_LENGTH)
>>> v2 = fnx(DOMAIN_LENGTH)
>>> v1
[7, 9, 5, 6, 6, 7, 6, 9, 8, 6, 6, 4, 5, 8]
>>> v2
[2, 2, 9, 7, 1, 4, 6, 9, 0, 7, 1, 9, 3, 0]
>>> len(v1); len(v2)
14
14
# create the child vector via crossover
>>> child_01 = crossover(v1, v2)
>>> child_01
[7, 9, 9, 7, 1, 4, 6, 9, 0, 7, 1, 9, 3, 0]
>>> len(child_01)
14
所以:
-
域大小(向量长度)为 5
- *crossover_point* 为 2,而 t
- 他的两个父向量是[4, 3, 2, 4, 8]和[1, 3, 1, 6, 3]
然后:
# fragment contributed from first parent:
>>> f1 = p1[:2]
>>> f1
[4, 3]
# fragment contributed from second parent:
>>> f2 = p2[2:]
>>> f2
[1, 6, 3]
# now just concatenate the two fragments to produce the child fragment
>>> child = f1 + f2
>>> child
[4, 3, 1, 6, 3]
>>> len(child) == len(p2)
True