One Max 问题:使用 Numpy¶
numpy 版本的一最大遗传算法示例与一最大短示例非常相似。个体类继承自 numpy.ndarray
。
import numpy
creator.create("Individual", numpy.ndarray, fitness=creator.FitnessMax)
第一个主要区别是实现了在 继承自 Numpy 教程中提到的复制机制的交叉函数。
def cxTwoPointCopy(ind1, ind2):
"""Execute a two points crossover with copy on the input individuals. The
copy is required because the slicing in numpy returns a view of the data,
which leads to a self overwriting in the swap operation. It prevents
::
>>> import numpy
>>> a = numpy.array((1,2,3,4))
>>> b = numpy.array((5,6,7,8))
>>> a[1:3], b[1:3] = b[1:3], a[1:3]
>>> print(a)
[1 6 7 4]
>>> print(b)
[5 6 7 8]
"""
size = len(ind1)
cxpoint1 = random.randint(1, size)
cxpoint2 = random.randint(1, size - 1)
if cxpoint2 >= cxpoint1:
cxpoint2 += 1
else: # Swap the two cx points
cxpoint1, cxpoint2 = cxpoint2, cxpoint1
ind1[cxpoint1:cxpoint2], ind2[cxpoint1:cxpoint2] \
= ind2[cxpoint1:cxpoint2].copy(), ind1[cxpoint1:cxpoint2].copy()
return ind1, ind2
此交叉功能被添加到工具箱中,而不是原始的 deap.tools.cxTwoPoint()
交叉功能。
toolbox.register("mate", cxTwoPointCopy)
第二个主要区别是 HallOfFame
中使用了 similar 函数,该函数必须设置为 numpy.array_equal()
或 numpy.allclose()
。
hof = tools.HallOfFame(1, similar=numpy.array_equal)
完整的源代码:examples/ga/onemax_numpy。