Skip to main content
 首页 » 编程设计

python之Scipy 优化 : Get the function to print out its iterations

2025年02月15日9davidwang456

我正在使用 scipy.optimize.minimize() 来最小化某个函数。我想比较不同方法的性能,BFGS 和 L-BFGS-B,为此,我希望函数打印出它的值和误差范围作为它正在优化。

L-BFGS-B 实际上会自动执行此操作,如下所示:

At X0         0 variables are exactly at the bounds 
 
At iterate    0    f=  7.73701D+04    |proj g|=  1.61422D+03 
 
At iterate    1    f=  4.33415D+04    |proj g|=  1.16289D+03 
 
At iterate    2    f=  9.97661D+03    |proj g|=  5.04925D+02 
 
At iterate    3    f=  4.10666D+03    |proj g|=  3.04707D+02 
 
.... 
 
At iterate  194    f=  3.34407D+00    |proj g|=  3.55117D-04 
 
At iterate  195    f=  3.34407D+00    |proj g|=  3.36692D-04 
 
At iterate  196    f=  3.34407D+00    |proj g|=  9.58307D-04 
 
Tit   = total number of iterations 
Tnf   = total number of function evaluations 
Tnint = total number of segments explored during Cauchy searches 
Skip  = number of BFGS updates skipped 
Nact  = number of active bounds at final generalized Cauchy point 
Projg = norm of the final projected gradient 
F     = final function value 
 
       * * * 
 
N    Tit     Tnf  Tnint  Skip  Nact     Projg        F 
243    196    205      1     0     0   9.583D-04   3.344D+00 
F =   3.34407234824719 

有谁知道我如何为 BFGS 做同样的事情?

注意:此问题与此处发布的更大问题相关:SciPy optimisation: Newton-CG vs BFGS vs L-BFGS ,关于这两种算法在特定优化问题中的行为差异。我想找出这两种算法的分歧所在。

请您参考如下方法:

我在这里找到了答案:How to display progress of scipy.optimize function?

optimize.minimize() 的callback 选项允许我们输入一个方法,该方法可以访问由 计算的变量 x_n code>optimize.minimize() 在时间步 n。我们可以用它来打印数据;我选择如下写出到外部文件:

##Print callback function 
def printx(Xi): 
    global Nfeval 
    global fout 
    fout.write('At iterate {0:4d},  f={1: 3.6f} '.format(Nfeval, energy(Xi)) + '\n') 
    Nfeval += 1 
 
Nfeval = 1 
fout = open('BFGS_steps_NN%d' %NN +'.txt','w') 
 
res = minimize(energy, xyzInit, method='BFGS', jac = energy_der, callback=printx, options={'disp': True}) 
fout.close() 

效果很好!