DEAP遗传算法

DEAP Genetic Algorithm

我目前在 Python 中使用 DEAP 作为遗传算法。我想创建一个长度为 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)

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

您可以查看其他示例here

您可以使用 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)

经过深思熟虑,我想到了这个解决方法:

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)

虽然有点难看,因为每次你想访问 Individual 类型的列表 individual 的内容时,你都必须调用 individual[0] 并迭代内容individual[0] 这看起来很多余。