MultiPoint crossover using Numpy

1.2k views Asked by At

I am trying to do crossover on a Genetic Algorithm population using numpy. I have sliced the population using parent 1 and parent 2.

population = np.random.randint(2, size=(4,8))
p1 = population[::2]
p2 = population[1::2]

But I am not able to figure out any lambda or numpy command to do a multi-point crossover over parents. The concept is to take ith row of p1 and randomly swap some bits with ith row of p2.

1

There are 1 answers

0
Tls Chris On

I think you want to select from p1 and p2 at random, cell by cell.

To make it easier to understand i've changed p1 to be 10 to 15 and p2 to be 20 to 25. p1 and p2 were generated at random in these ranges.

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]])

The numbers in the teens come from p1 when sieve is 1 The numbers in the twenties come from p2 when sieve is 0

This may be able to be made more efficient but is this what you expect as output?