Numpy Array random mutation

Viewed 1593

I'm coding my first genetic algorithm in Python. I particularly care about the optimization and population scalability.

import numpy as np
population = np.random.randint(-1, 2, size=(10,10))

Here I make a [10,10] array, with random number between -1 and 1.
And now I want to perform a specific mutation ( mutation rate depends on the specimens fitness ) for each specimen of my array.

For example, I have:

print population
[[ 0  0  1  1 -1  1  1  0  1  0]
[ 0  1 -1 -1  0  1 -1 -1  0 -1]
[ 0  0  0  0  0  0  0  0  0  0]
[ 0  0  0  0  0  0  0  0  0  0]
[ 0  0  0  0  0  0  0  0  0  0]
[ 0  1  1  0  0  0  1  1  0  1]
[ 1 -1  0  0  1  0 -1  1  1  0]
[ 1 -1  1 -1  0 -1  0  0  1  1]
[ 0  0  0  0  0  0  0  0  0  0]
[ 0  1  1  0  0  0  1 -1  1  0]]

I want to perform the mutation of this array with a specific mutation rate for each sub-array in population. I try this but the optimization is not perfect and I need to perform a different mutation for each sub-array (each sub-array is a specimen) in the population (the main array, "population").

population[0][numpy.random.randint(0, len(population[0]), size=10/2)] = np.random.randint(-1, 2, size=10/2)

I'm looking for a way to apply something like a mutation mask on all the main-array. Something like that:

 population[array element select with the mutation rate] = random_array[with the same size]

I think it's the best way (because we only to an array selection and after we replace this selection with the random array), but I don't know how to perform this. And if you have other solution I am on it ^^.

1 Answers
Related