Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DEAP toolbox: to consider different types and ranges of genes in mutation and crossover operators

I am working on a genetic algorithm implementation and I'm using DEAP toolbox. I've written a code that initializes chromosomes which their first gene is a float number in range of [0.01, 2048], their second gene is again float in range of [0.0001, 10] and their last three genes are boolean. This is my code:

toolbox.register("attr_flt1", random.uniform, 0.01, 2048)
toolbox.register("attr_flt2", random.uniform, 0.0001, 10)
toolbox.register("attr_bool", random.randint, 0, 1)
enter ctoolbox.register("individual", tools.initCycle, creator.Individual,
             (toolbox.attr_flt1, toolbox.attr_flt2, toolbox.attr_bool, toolbox.attr_bool, toolbox.attr_bool),
             n=1)

There is a sample of created population:

[1817.2852738610263, 6.184224906600851, 0, 0, 1], [1145.7253307024512, 8.618185266721435, 1, 0, 1], ...

Now, I want to do mutation and crossover on my chromosomes by considering differences in the genes types and ranges. Currently I have an error because a 0 value is produced for the first gene of a chromosome ,after applying crossover and mutation operators, which is wrong with my evaluation function. Can anyone help me code selection, mutation and crossover using DEAP toolbox that produce new population in ranges defined at first?

like image 785
Saeide Avatar asked Oct 28 '22 22:10

Saeide


1 Answers

If you use the mutation operator mutPolynomialBounded (documented here), then you can specify the interval for each gene.

With the bounds you indicated, perhaps using something such as

eta = 0.5 #indicates degree of ressemblance of mutated individual
indpb = 0.1 #probability of individual to be mutated
low = [0.01, 0.0001, 0, 0, 0] #lower bound for each gene
up = [2048, 10, 1, 1, 1] #upper bound for each gene
toolbox.register('mutate', mutPolynomialBounded(individual, eta, low, up, indpb))

as a mutation function will solve your error. This way, first gene is in the interval [0.01, 2048], the second gene is in the interval [0.0001, 10] and the last three genes are in the interval [0, 1].


If you also want the last three genes to be either 0 or 1 (but not a float in between), then you might have to implement your own mutation function. For instance, the following function will select random values for each gene using your requirements

def mutRandom(individual, indpb):
    if random.random() < indpb:
        individual[0] = toolbox.attr_flt1()
        individual[1] = toolbox.attr_flt2()
        for i in range(2, 5):
            individual[i] = toolbox.attr_bool()
    return individual,
like image 194
usernumber Avatar answered Jan 02 '23 19:01

usernumber