繁体   English   中英

Python DEAP 和 Windows 上的多处理:AttributeError

[英]Python DEAP and multiprocessing on Windows: AttributeError

我有以下情况:

  • Windows 10
  • Python 3.7
  • 深沉的 1.3.1

有一个 main.py

def main():
    ...
    schedule.schedule()
    ...

if __name__== "__main__":
    main()

然后,我还有一个文件 schedule.py

def schedule()
   ...
    toolbox = base.Toolbox()

    creator.create("FitnessMin", base.Fitness, weights=(-1.0,))
    creator.create("Individual", list, fitness=creator.FitnessMin)

    toolbox.register('individual', init_indiv, creator.Individual, bounds=bounds)
    toolbox.register("population", tools.initRepeat, list, toolbox.individual)

    toolbox.register("evaluate", fitness, data=args)
    toolbox.register("mate", tools.cxTwoPoint)
    toolbox.register("mutate", tools.mutFlipBit, indpb=0.05)
    toolbox.register("select", tools.selTournament, tournsize=3)

    # Further parameters
    cxpb = 0.7
    mutpb = 0.2

    # Measure how long it takes to caluclate 1 generation
    MAX_HOURS_GA = parameter._MAX_HOURS_GA
    POPSIZE_GA = parameter._POPSIZE_GA
    pool = multiprocessing.Pool(processes=4)
    toolbox.register("map", pool.map)
    pop = toolbox.population(n=POPSIZE_GA * len(bounds))
    result = algorithms.eaSimple(pop, toolbox, cxpb, mutpb, 1, verbose=False)

现在,执行它会给我以下错误:

Process SpawnPoolWorker-1:
Traceback (most recent call last):
  File "C:\Users\...\lib\multiprocessing\process.py", line 297, in _bootstrap
    self.run()
  File "C:\Users\...\lib\multiprocessing\process.py", line 99, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\...\lib\multiprocessing\pool.py", line 110, in worker
    task = get()
  File "C:\Users\...\lib\multiprocessing\queues.py", line 354, in get
    return _ForkingPickler.loads(res)
AttributeError: Can't get attribute 'Individual' on <module 'deap.creator' from 'C:\\Users...

现在,我确实注意到 DEAP 文档( https://deap.readthedocs.io/en/master/tutorials/basic/part4.html )说

警告 如多处理指南中所述,在 Windows 下,由于进程的初始化方式,必须在 >if __name__ == "__main__" 部分中保护进程池。

但这并没有真正帮助我,因为我当然不想在我的 main 中拥有所有toolbox.register(...) ,甚至可能无法这样做。 只是移动池的创建

    pool = multiprocessing.Pool(processes=4)
    toolbox.register("map", pool.map)

对主要没有帮助。

似乎还有其他人有类似的问题,甚至最近( https://github.com/rsteca/sklearn-deap/issues/59 )。 对于他们中的大多数人来说,似乎存在某种解决方法,但它们似乎都不适合我的情况,或者至少我不知道如何让它们工作。 我也尝试过按照注册函数和初始化池的顺序移动,但没有运气。 我也尝试过使用 SCOOP,但结果相似。

有任何想法吗?

解决方法是在全局scope中创建“FitnessMin”和“Individual”,即在main.py中:

import ...

creator.create("FitnessMin", base.Fitness, weights=(-1.0,))
creator.create("Individual", list, fitness=creator.FitnessMin)

def main():
    ...
    schedule.schedule()
    ...

if __name__== "__main__":
    main()

暂无
暂无

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

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