如何解决SciPy 优化与类方法并行运行
我手头有一项复杂的任务,我的目标是最小化定义为类方法的黑盒函数。这是一项耗时的任务,因此我决定通过并行运行该函数来进行优化。使用的操作系统是 Windows 10 - 64 位和 Python 版本 3.6.6 和 SciPy 1.5.1。
我在编码时注意到,如果我在并行执行模式下(使用 workers = -1
)调用优化器之前设置类属性,则不会设置类属性,而是使用默认值。
我是否尝试在优化器代码之前直接设置类属性或通过类构造函数设置类属性都没有关系。在调用代码的并行部分之前,如何确保正确设置了此类属性?
此外,优化代码要从另一个驱动文件中调用;因此将代码放在 if __name__ == '__main__':
下将不会执行它。有解决方法吗?
请参阅以下 MWE 代码。请注意,该函数在执行时返回参数乘以 5 的平方,而不是要使用的实际值 10。非常感谢您提供有关如何解决这些问题的任何见解/建议。
from scipy.optimize import brute,rosen
from pyinstrument import Profiler
class DummyClass:
multp = 5
def __init__(self,mul):
self.__class__.multp = mul
@classmethod
def square(cls,x):
# calculate the square of the value of x
return -x[0]*x[0]*cls.multp
if __name__ == '__main__':
profiler = Profiler()
profiler.start()
rranges = (slice(-4,4,0.00001),)
inst = DummyClass(10)
# Finish function confuses the optimizer and value not on the initial grid is returned
result = brute(func=inst.square,ranges=rranges,full_output=True,finish=None,workers=-1)
print(f"The minimum of the function is at {result[0]:.2f} and the value is {result[1]:.2f}")
profiler.stop()
print(profiler.output_text(unicode=True,color=True))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。