如何在 scipy.optimize.differential_evolution 中将参数传递给回调函数

How to pass arguments to callback function in scipy.optimize.differential_evolution

我正在使用 scipy.optimize 中的 differential_evolution 来解决我的优化问题。我的优化器采用一些参数进行优化。

代码 -

res = optimize.differential_evolution(objective,bounds,args=arguments,disp=True,callback = callback_DE(arguments))

我还有一个回调函数。我想将我的参数发送到我的回调函数,这就是我的问题出现的地方。

如果我不向我的回调函数传递任何参数,它工作正常 -

def callback_DE(x,convergence):        
   '''
   some code
   '''

但是,如果我在函数定义中将 arguments 作为参数,例如 -

def callback_DE(x,convergence,arguments):        
   '''
   some code
   '''

它抛出一个错误。

向回调函数传递参数的正确方法是什么?

这是不可能的。您只能使用提供给您的两个值。回调的要点是跟随你的优化,如果你选择根据它满足的某些条件这样做,通过返回 True.

来提前停止它

有关详细信息,请参阅 reference 中的说明:

callback : callable, callback(xk, convergence=val), optional

A function to follow the progress of the minimization. xk is the current value of x0. val represents the fractional value of the population convergence. When val is greater than one the function halts. If callback returns True, then the minimization is halted (any polishing is still carried out).

如果你真的需要使用参数,你应该直接从函数内部访问它们。

偶然地,我找到了一种方法来做到这一点。您需要使用 functools.partial 来实现。

下面是一个小例子:

    from functools import partial
    # the callback function with two 'undesired' arguments
    def print_fun_DE(xk, convergence, name, method):
    print('for {} by {} : x= {} on convergence = {} '.format(name, method, xk,convergence))
    # the way we call this callback function:
    callback=partial(print_fun_DE, name=data_name, method=method),