2016-11-09 209 views
1

我目前在Python中使用DEAP進行遺傳算法。我想創建一個長度爲no_sensors的初始人羣。我的問題是,由於random.choice(nodes)函數,一些節點最終是相同的,並且最初的長度結束小於no_sensors。我在想,如果有解決這個問題的方式:DEAP遺傳算法

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

回答

0

經過一番思考,我想出了這個解決辦法:

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) 

這是一個有點難看不過,因爲每次你要訪問的內容individualIndividual類型,你必須打電話individual[0]並重復individual[0]這似乎是相當多餘的內容。

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) 
+0

但問題是,如果random.choice選擇兩次相同的值,我希望它算作一個。基本上,我需要列表中的固定長度的唯一項目:節點。我正在考慮使用random.sample(nodes,no_sensors),但我似乎無法將其納入代碼而不會產生錯誤。 – meraxes

+0

一個集合不能包含列表,因爲它們是可變的,因此不可哈希.'set([[1,2,3],3]) TypeError:不可能的類型:'list'' –

+0

哦,對!我將個人的基礎改爲列表。即使如此,列表中的列表看起來也是多餘的。 – meraxes