在一定时间后,使用scipy.optimize。中的回调函数来停止进程

时间:2019-05-16 20:35:55

标签: python scipy

我正在尝试在scipy.optimize.differential_evolution方法中使用callback参数,以在某些指定的max_time参数之后停止最小化过程。

下面的代码显然到达了callbackF()函数,然后再也到达了。

我在这里做什么错了?


from scipy.optimize import differential_evolution as DE
import time as t

# Max time in seconds
max_time = 3.

def callbackF(start_t):
    time_elapsed = t.time() - start_t
    if time_elapsed > max_time:
        print("Stop")
        return True

def DEdist(model):
    res = (1. - model[0])**2 + 100.0 * (model[1] - model[0]**2)**2 + \
        (1. - model[1])**2 + 100.0 * (model[2] - model[1]**2)**2
    return res

start_t = t.time()
bounds = [[0., 10.], [0., 10.], [0., 10.], [0., 10.]]
result = DE(
    DEdist, bounds, popsize=100, maxiter=1500, callback=callbackF(start_t))
print(t.time() - start_t)

1 个答案:

答案 0 :(得分:2)

您正在传递调用callbackF(start_t)的返回值。您想要的是传递函数本身。这是做到这一点的一种方法

from scipy.optimize import differential_evolution as DE
import time as t

# Max time in seconds
max_time = 3.

def get_callback(start_t):
    def callbackF(current_params, convergence):
        time_elapsed = t.time() - start_t
        if time_elapsed > max_time:
            print("Stop")
            return True
    return callbackF

def DEdist(model):
    res = (1. - model[0])**2 + 100.0 * (model[1] - model[0]**2)**2 + \
        (1. - model[1])**2 + 100.0 * (model[2] - model[1]**2)**2
    return res

start_t = t.time()
bounds = [[0., 10.], [0., 10.], [0., 10.], [0., 10.]]
result = DE(
    DEdist, bounds, popsize=100, maxiter=1500, callback=get_callback(start_t))
print(t.time() - start_t)

我添加了*args, **kwargs,因为传入了一些kwarg调用convergence,并且我不想在文档中查找是否还有传递给回调函数的东西。

编辑-使函数签名更有意义。