1

我目前正在将 DEAP 用于 Python 中的遗传算法。我想创建一个具有长度的初始人口no_sensors。不过我的问题是,由于random.choice(nodes)函数的原因,一些节点最终是相同的,并且初始长度最终小于no_sensors. 我想知道是否有办法解决这个问题:

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)

基本上,我需要 list 中固定长度的唯一项目nodes。我正在考虑使用random.sample(nodes, no_sensors),但我似乎无法将其合并到代码中而不会产生错误

您可以在此处查看其他示例。

4

2 回答 2

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.

于 2016-11-13T19:28:54.643 回答
0

您可以使用functools.partialrandom.sample

from functools import partial
import random
no_sensors = 5
mysample = partial(random.sample,k=no_sensors)
toolbox.register("attr_item", mysample, nodes)
于 2016-11-09T14:04:30.697 回答