1

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.

meraxes
  • 541
  • 10
  • 23

2 Answers2

0

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)
Sebastian Wozny
  • 16,943
  • 7
  • 52
  • 69
  • The problem though is that if random.choice selects the same value twice, I want it to count as one. 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. – meraxes Nov 09 '16 at 14:11
  • a set can't contain lists because they're mutable and therefore not hashable.`set([[1,2,3],3]) TypeError: unhashable type: 'list'` – Sebastian Wozny Nov 09 '16 at 14:42
  • Oh, right! I changed the base of Individual into a list. Even still, a list within a list would seem redundant. – meraxes Nov 09 '16 at 14:50
0

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.

meraxes
  • 541
  • 10
  • 23