I am using DEAP package in Python to write a program for optimization with evolutionary algorithm specifically with Genetic.
I need to create chromosomes by using list type in python. This chromosome should have five float genes (alleles) in different ranges.
My main problem is to create such a chromosome. However, it would be better if I could use tools.initRepeat function of deap package for this.
For the cases in which all the genes are in the same range we could use the following code:
import random
from deap import base
from deap import creator
from deap import tools
creator.create("FitnessMax", base.Fitness, weights=(1.0,))
creator.create("Individual", list, fitness=creator.FitnessMax)
IND_SIZE=10
toolbox = base.Toolbox()
toolbox.register("attr_float", random.random)
toolbox.register("individual", tools.initRepeat, creator.Individual,
toolbox.attr_float, n=IND_SIZE)
That I got from here.
I found a good recommendation here.
def genFunkyInd(icls, more_params):
genome = list()
param_1 = random.uniform(...)
genome.append(param_1)
param_2 = random.randint(...)
genome.append(param_2)
# etc...
return icls(genome)
The icls
(standing for individual class) parameter should receive the type created with the creator, while all other parameters configuring your ranges can be passed like the more_params
argument or with defined constants in your script. Here is how it is registered in the toolbox.
toolbox.register('individual', genFunkyInd, creator.Individual, more_params)
It manually creates a class for chromosome. I don't know if it is the best choice but it can be used to solve my problem.