在 scipy.differential_evolution 中执行 workers 参数时出错 [英] Error when executing the workers parameter in scipy.differential_evolution

查看:61
本文介绍了在 scipy.differential_evolution 中执行 workers 参数时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试了解差分进化方法的并行执行.我使用了

有人可以建议一种方法来解决这个问题.

解决方案

那个 Scipy 函数使用了 multiprocessing 模块.因此,我们必须通过使用 if __name__ == '__main__'"来保护程序的入口点.如文档所坚持在安全导入主模块"一节中.

if __name__ == '__main__':从 scipy.optimize 进口罗森,差异进化边界 = [(0,2), (0, 2), (0, 2), (0, 2), (0, 2)]结果=差异进化(玫瑰,边界,更新=延期",工人=2)打印(结果)

Scipy 文档中的示例在交互式 Python 会话中运行,这不是必需的.但是当作为脚本运行时,我们必须添加代码围栏以避免您遇到的错误.否则,优化运行会在多个进程中的每一个进程中一遍又一遍地启动.

在 Linux 上运行脚本时也不需要代码围栏.在该平台上,默认 启动方法" 对于工作进程是fork";(如错误消息中所述)而不是spawn"就像在 Windows 和 macOS 上一样.叉子"方法更轻量级,避免重新启动 Python 解释器,这就是不需要保护入口点的原因.

I'm trying to learn about parallel execution for Differential Evolution method. I used the example found on the documentation:

from scipy.optimize import rosen, differential_evolution
bounds = [(0,2), (0, 2), (0, 2), (0, 2), (0, 2)]
result = differential_evolution(rosen, bounds, updating='deferred',workers=2)

But it throws the following error:

Can somebody please suggest a method to solve this issue.

解决方案

That Scipy function uses the multiprocessing module under the hood if the workers argument is supplied. We must therefore "protect the entry point of the program by using if __name__ == '__main__'" as the documentation insists in section "Safe importing of main module".

if __name__ == '__main__':
    from scipy.optimize import rosen, differential_evolution
    bounds = [(0,2), (0, 2), (0, 2), (0, 2), (0, 2)]
    result = differential_evolution(rosen, bounds, updating='deferred',workers=2)
    print(result)

The example from the Scipy documentation is run in an interactive Python session where this is not necessary. But when run as a script, we must add the code fence to avoid the error you encountered. Otherwise the optimization run is started over and over again in each of the multiple processes.

The code fence is also not necessary when running the script on Linux. On that platform, the default "start method" for the worker processes is "fork" (as mentioned in the error message) and not "spawn" as on Windows and macOS. The "fork" method is more lightweight and avoids restarting the Python interpreter, which is why the entry point need not be protected.

这篇关于在 scipy.differential_evolution 中执行 workers 参数时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆