我正在使用Python包deap。 我的问题是从数据集中获取我的人口从基因生成它。 例如: 我有[[1,2,0,0,...],[1,3,4,0,...],...]作为数据集 我想从这个数据集中选择随机的n个元素作为我的人口。 下面是使用随机二进制数0或1的群体的代码,并且len中的向量是100:
import random
from deap import base
from deap import creator
from deap import tools
creator.create("FitnessMax", base.Fitness, weights=(1.0,))
creator.create("Individual", list, fitness=creator.FitnessMax)
toolbox = base.Toolbox()
toolbox.register("attr_bool", random.randint, 0, 1)
toolbox.register("individual", tools.initRepeat, creator.Individual,
toolbox.attr_bool, 100)
# define the population to be a list of individuals
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
请注意,我可以简单地使用random.sample(Data_set,Num_of_ind) 为了使我的人口,但这不适用于deap包。 我需要一个使用Deap包的解决方案。
答案 0 :(得分:0)
实际上,您可以在DEAP中使用random.sample()。您只需注册该功能,然后在注册时将其传递给个人:
# Example of dataset (300 permutations of [0,1,...,99]
data_set = [random.sample(range(100), 100) for i in range(300)]
toolbox = base.Toolbox()
# The sampling is used to select one individual from the dataset
toolbox.register("random_sampling", random.sample, data_set, 1)
# An individual is generated by calling the function registered in
# random_sampling, with the input paramters given
toolbox.register("individual", tools.initIterate, creator.Individual, toolbox.random_sampling)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
请注意,每个人都将由包含值列表的列表组成(类似[[7, 40, 87, ...]]
。如果要删除外部列表(改为使用[7, 40, 87, ...]
),则应替换{ {1}} by:
random_sampling