我目前正在使用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)基本上,我需要一个固定长度的唯一项目从列表nodes。我正在考虑使用random.sample(nodes, no_sensors),但我似乎无法在不引起错误的情况下将其合并到代码中
您可以查看其他示例这里。
发布于 2016-11-13 19:28:54
经过一番思考,我想出了一个解决办法:
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的list Individual的内容时,都必须调用individual[0]并迭代individual[0]的内容,这看起来相当多余。
发布于 2016-11-09 14:04:30
您可以使用functools.partial和random.sample
from functools import partial
import random
no_sensors = 5
mysample = partial(random.sample,k=no_sensors)
toolbox.register("attr_item", mysample, nodes)https://stackoverflow.com/questions/40508825
复制相似问题