meraxes meraxes - 1 year ago 185
Python Question

DEAP Genetic Algorithm

I'm currently using DEAP for the genetic algorithm in Python. I want to create an initial population of individuals that have length

. My problem though is that due to the
function, some nodes end up being the same and the initial length ends up being less than
. I was wondering if there's a way to fix this:

creator.create("FitnessMax", base.Fitness, weights=(2.0, -1.0))
creator.create("Individual", set, fitness=creator.FitnessMax)

toolbox = base.Toolbox()
toolbox.register("attr_item", random.choice, nodes)
toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_item, n=no_sensors)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)

Basically, I need a fixed length of unique items from the list
. I was thinking of using
random.sample(nodes, no_sensors)
but I can't seem to incorporate that into the code without incurring errors

You can check out other example here.

Answer Source

After some thought, I came up with this workaround:

creator.create("FitnessMax", base.Fitness, weights=(2.0, -1.0))
creator.create("Individual", list, fitness=creator.FitnessMax)

toolbox = base.Toolbox()
toolbox.register("attr_item", random.sample, nodes, no_sensors)
toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_item, n=1)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)

It's a bit ugly though, since everytime you want to access the content of the list individual of type Individual, you'd have to call individual[0]and iterate the content of individual[0] which seems pretty redundant.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download