python—如何在deap中将参数传递给“toolbox.population”

xuo3flqw  于 2021-09-13  发布在  Java
关注(0)|答案(0)|浏览(232)

我试图在deap中创建一个自定义的“个人”。原因是个体是由几个解释变量组成的。每个解释变量都有下限和上限。此外,它可能具有步长或精度。
这是我正在研究的代码:

import random
from deap import base, creator, tools
from typing import Optional, List, Any

creator.create("FitnessMin", base.Fitness, weights=(-1.0,))   
creator.create("Individual", list, fitness=creator.FitnessMin)   # individual data-type : List
toolbox = base.Toolbox()

'''
Functions
'''

def random_pick(lower: float, upper: float, step: Optional[int] = None) -> float:
    # Pick random numbers within specified bounds 
    if step is None:
        return random.uniform(lower, upper)
    else:
        candidates_num = round((upper - lower) / step)
        return lower + random.randint(0, candidates_num) * step

def make_individual(explanatories) -> List[Any]:
     individual = []
     for explanatory in explanatories:
         individual.append(
             random_pick(
                 lower=explanatories[explanatory][0],
                 upper=explanatories[explanatory][1],
                 step=explanatories[explanatory][2] if len(explanatories[explanatory]) == 3 else None,
             )
         )
     return creator.Individual(individual)

'''
Main
'''
pop_size = 10

explanatories={
    "a": (30, 100, 1),   # (low, high, step)
    "b": (80, 200, 1),
    "c": (15, 80, 1),
    "d": (1.5, 5, 0.1),
    "e": (15, 200, 1),
    "f": (5, 1699, 1),
    "g": (0.5, 0.5),     # (low, high)
    }

toolbox.register("individual", make_individual)

# Check value of individual

ind = toolbox.individual(explanatories)   # list

# Population (following is the Bag type of population which is common)

toolbox.register("population", tools.initRepeat, list, toolbox.individual)

# Check population

pop = toolbox.population(pop_size)   # ERROR

作用 random_pick 通过考虑步长,随机选取上下限内所有解释的值。和功能 make_individual 负责制定个人计划。
上面代码的问题是我试图使人口增加的地方。当我运行以下行时:

pop = toolbox.population(pop_size)

我得到一个错误:

TypeError: make_individual() missing 1 required positional argument: 'explanatories'

我的问题是,在生成总体时,如何将解释作为输入参数传递给“toolbox.population”或“make_individual()”。
谢谢你的帮助。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题