scipy优化与类方法并行运行

r8xiu3jd  于 2021-07-13  发布在  Java
关注(0)|答案(0)|浏览(152)

我手头有一项复杂的任务,我的目标是最小化定义为类方法的黑盒函数。这是一项耗时的任务,因此我决定通过并行运行函数来进行优化。使用的操作系统是Windows10-64位,python版本是3.6.6和SCIPY1.5.1。
我在编写代码时注意到,如果在以并行执行模式调用优化器之前设置类属性(使用 workers = -1 )未设置class属性,使用默认值。
在为优化器编写代码之前,我是尝试直接设置class属性还是通过类构造函数设置class属性并不重要。如何确保在调用代码的并行部分之前正确设置了这个类属性?
此外,将从另一驱动程序文件调用优化代码;因此将代码置于 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))

暂无答案!

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

相关问题