简体   繁体   English

DEAP遗传算法

[英]DEAP Genetic Algorithm

I'm currently using DEAP for the genetic algorithm in Python. 我目前正在使用DEAP进行Python中的遗传算法。 I want to create an initial population of individuals that have length no_sensors . 我想创建一个长度为no_sensors的初始个体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 . 我的问题是,由于random.choice(nodes)函数,一些节点最终是相同的,初始长度最终小于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 . 基本上,我需要列表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 我正在考虑使用random.sample(nodes, no_sensors)但我似乎无法将其合并到代码中而不会产生错误

You can check out other example here . 你可以在这里查看其他例子。

You can use functools.partial and random.sample : 您可以使用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)

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. 这是一个有点难看不过,因为每次要访问列表的内容individual类型的Individual ,你必须调用individual[0]和迭代的内容individual[0]这似乎相当多余。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM