在最大运行时间后停止scipy.optimize.minimize

时间:2015-11-30 13:20:06

标签: python scipy runtime minimize

我在群集上运行scipy.optimize.minimize(使用'L-BFGS-B' - 算法)。运行时间超过72小时的任务将被终止,无需保存结果。在T = 48h的运行时间过后,有没有办法退出scipy.optimize.minimize?

1 个答案:

答案 0 :(得分:0)

  1. 一种方法是估算一次迭代的评估时间,然后在maxiter参数中设置options

  2. 另一种方法是定义一个类,该类修改函数fun,使其在指定时间后返回错误,并记录最后的输入值x及其输出{{1 }}:

    fun(x)

    因此,可以在调用from scipy.optimize import minimize import numpy as np import time class TimedFun: def __init__(self, fun, stop_after=10): self.fun_in = fun self.started = False self.stop_after = stop_after def fun(self, x): if self.started is False: self.started = time.time() elif abs(time.time() - self.started) >= self.stop_after: raise ValueError("Time is over.") self.fun_value = self.fun_in(x) self.x = x return self.fun_value 之后(例如,在第一次调用之后2秒之后)停止优化:

    fun

顺便说一句,签出我的软件包optimparallel,这使您可以通过并行计算加快优化速度,并返回每个软件包的评估值## Objective function: def fun(x): time.sleep(5) return sum(x**2) ## Minimize with early stopping: fun_timed = TimedFun(fun=fun, stop_after=2) try: minimize(fun=fun_timed.fun, x0=np.array([100]), method='L-BFGS-B') except Exception as e: print("Error: " + str(e)) # Error: Time is over. ## Retrieve last evaluated `x` and `fun(x)`: print('x=', fun_timed.x, ', fun(x)=', fun_timed.fun_value, sep='') # x=[100.], fun(x)=10000.0 xfun(x)步骤。

jac(x)