如何使用np.arange基于指定基因空间生成符合Deap规范的种群?
问题原因
你之前三个尝试的核心问题是对Deap的initCycle和initRepeat两个接口的职责理解错误:
- 尝试2的
n=10写在了initCycle的参数里,这个参数代表「将所有属性的生成逻辑重复多少次拼接为单个个体」,不是生成多少个个体。如果这里设10,你得到的单个个体会是长度5*10=50的列表,不符合预期。 - 尝试3给每个属性注册了返回10个值的采样逻辑,导致单个个体变成嵌套列表结构,不符合Deap要求的「单个体为一维列表,每个元素对应一个基因」的结构,因此触发类型错误。
修正代码
直接基于你的尝试2修改即可,完全不需要重写主逻辑:
import random import numpy as np from deap import base, creator, tools # 你原有的基因空间定义 gene_space = [ {"name": "length",'high':110,'low':10,'step':10}, {"name": "emaLength",'high':34,'low':1,'step':2}, {"name": "averageLength",'high':110,'low':10,'step':10}, {"name": "factor",'high':0.5,'low':0.02,'step':0.02}, {"name": "criticalValue",'high':60,'low':-50,'step':10}, ] # 定义最大化适应度函数 creator.create("FitnessMax", base.Fitness, weights=(1.0,)) # 创建个体类,为附带适应度属性的列表类型 creator.create("Individual", list, fitness=creator.FitnessMax) # 初始化toolbox实例 toolbox = base.Toolbox() list_of_attrs = [] # 遍历基因空间注册单个基因的生成逻辑(直接复用你尝试2的正确逻辑) for conf in gene_space: value_range = np.arange(conf['low'], conf['high'], conf['step']) # 每次调用返回单个随机可选值 toolbox.register(conf["name"], random.choice, value_range) list_of_attrs.append(conf["name"]) # 注册个体构造:n=1代表每个个体只取一轮所有属性,长度和基因数量一致(5) toolbox.register("individual", tools.initCycle, creator.Individual, (getattr(toolbox, key) for key in list_of_attrs), n=1) # 注册种群构造:n=10代表生成10个个体组成种群,此处参数才是控制种群大小的配置 toolbox.register("population", tools.initRepeat, list, toolbox.individual, n=10) # 你原有其他注册逻辑保持不变 toolbox.register("mate", tools.cxTwoPoint) toolbox.register("mutate", tools.mutGaussian, mu=0, sigma=1, indpb=0.1) toolbox.register("select", tools.selTournament, tournsize=3) toolbox.register("evaluate", evaluate)
验证方式
调用pop = toolbox.population()生成种群后,你可以自行确认类型符合Deap官方要求:
- 种群本身是普通列表类型,每个元素都是
creator.Individual类的实例 - 每个个体自带
fitness属性,结构和官方示例完全一致,可直接接入Deap自带的进化算法逻辑
额外注意
你当前使用的mutGaussian高斯变异会生成超出你定义取值范围、步长的浮点值,如果需要严格限制基因在你预设的可选值内,可以替换为自定义变异逻辑,随机将目标基因替换为同属性的其他可选值即可。
内容的提问来源于stack exchange,提问作者wildcat89
相关产品推荐
相关产品推荐

