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 numpy.ndarray.

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((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
    
    

This crossover function is added to the toolbox instead of the original deap.tools.cxTwoPoint() crossover.

toolbox.register("mate", cxTwoPointCopy)

The second major difference is the use of the similar function in the HallOfFame that has to be set to a numpy.array_equal() or numpy.allclose()

    hof = tools.HallOfFame(1, similar=numpy.array_equal)

The complete source code: examples/ga/onemax_numpy.

Previous topic

One Max Problem: Short Version

Next topic

Knapsack Problem: Inheriting from Set

This Page