【问题标题】:Scipy optimisation: Get the function to print out its iterationsScipy 优化:获取函数以打印出其迭代
【发布时间】:2017-07-15 14:30:37
【问题描述】:

我正在使用scipy.optimize.minimize()来最小化某个功能。我想比较不同方法的性能,BFGSL-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,关于这两种算法在特定优化问题中的行为之间的差异。我想追踪这两种算法的分歧点。

【问题讨论】:

  • minimize 采用 callback 参数。这是一个用户定义的函数,可以在每个信息处显示信息。 SO问题中可能有一些示例。
  • @hpaulj 我在下面写了一个答案。看看吧。

标签: python numpy optimization scipy


【解决方案1】:

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

optimize.minimize()callback 选项允许我们输入一个方法,该方法可以访问由optimize.minimize() 在时间步n 计算的变量x_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()

效果很好!

【讨论】:

    猜你喜欢
    • 2022-08-11
    • 1970-01-01
    • 2016-02-04
    • 2022-01-08
    • 2020-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-15
    相关资源
    最近更新 更多