Skip to main content
 首页 » 编程设计

python之scipy.optimize.differential_evolution 评估了多少次要最小化的函数

2024年11月24日8findumars

我正在尝试申请 this answer在我的代码中显示 scipy.optimize.differential_evolution 的进度条方法。

我以为 differential_evolution 会评估 func(被调用的函数被最小化)popsize * maxiter 次,但显然这是不是这样的。

下面的代码应该显示一个进度条,该进度条会增加到 100%:

[####################] 100%  

但实际上,随着 DEdist() 函数比 popsize * maxiter(我将其用作 total updt() 函数的参数。

如何计算 differential_evolution 执行的函数求值总数?这完全可以做到吗?


from scipy.optimize import differential_evolution as DE 
import sys 
 
 
popsize, maxiter = 10, 50 
 
 
def updt(total, progress, extra=""): 
    """ 
    Displays or updates a console progress bar. 
 
    Original source: https://stackoverflow.com/a/15860757/1391441 
    """ 
    barLength, status = 20, "" 
    progress = float(progress) / float(total) 
    if progress >= 1.: 
        progress, status = 1, "\r\n" 
    block = int(round(barLength * progress)) 
    text = "\r[{}] {:.0f}% {}{}".format( 
        "#" * block + "-" * (barLength - block), 
        round(progress * 100, 0), extra, status) 
    sys.stdout.write(text) 
    sys.stdout.flush() 
 
 
def DEdist(model, info): 
    updt(popsize * maxiter, info['Nfeval'] + 1) 
    info['Nfeval'] += 1 
 
    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 
 
 
bounds = [[0., 10.], [0., 10.], [0., 10.], [0., 10.]] 
result = DE( 
    DEdist, bounds, popsize=popsize, maxiter=maxiter, 
    args=({'Nfeval': 0},)) 

请您参考如下方法:

来自 help(scipy.optimize.differential_evolution):

maxiter : int, optional 
    The maximum number of generations over which the entire population is 
    evolved. The maximum number of function evaluations (with no polishing) 
    is: ``(maxiter + 1) * popsize * len(x)`` 

默认情况下 polish=True:

polish : bool, optional 
    If True (default), then `scipy.optimize.minimize` with the `L-BFGS-B` 
    method is used to polish the best population member at the end, which 
    can improve the minimization slightly. 

所以你需要改变两件事:

1 在这里使用正确的公式:

updt(popsize * (maxiter + 1) * len(model), info['Nfeval'] + 1) 

2 传递 polish=False 参数:

result = DE( 
    DEdist, bounds, popsize=popsize, maxiter=maxiter, polish=False, 
    args=({'Nfeval': 0},)) 

之后您会看到进度条恰好在达到 100% 时停止。