1
votes

I'm currently using DEAP for the genetic algorithm in Python. I want to create an initial population of individuals that have length no_sensors. My problem though is that due to the random.choice(nodes) function, some nodes end up being the same and the initial length ends up being less than no_sensors. 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 nodes. 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.

2
Is no_sensors set in advance or is its value possibly different for each individual? - usernumber

2 Answers

0
votes

You can use functools.partial and random.sample:

from functools import partial
import random
no_sensors = 5
mysample = partial(random.sample,k=no_sensors)
toolbox.register("attr_item", mysample, nodes)
0
votes

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.