One Max Problem: Using Numpy¶
The numpy version one max genetic algorithm example is very similar to one max
short example. The individual class is inherited from the
import numpy creator.create("Individual", numpy.ndarray, fitness=creator.FitnessMax)
The first major difference is the crossover function that implements the copying mechanism mentionned in the Inheriting from Numpy tutorial.
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 overwritting in the swap operation. It prevents :: >>> import numpy >>> a = numpy.array((1,2,3,4)) >>> b = numpy.array((126.96.36.199)) >>> 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
This crossover function is added to the toolbox instead of the original
hof = tools.HallOfFame(1, similar=numpy.array_equal)
The complete source code: examples/ga/onemax_numpy.