我正在使用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,关于特定优化问题中这两种算法之间的行为差​​异。我想找出这两种算法的区别所在。

最佳答案

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

callbackoptimize.minimize()选项允许我们提供一种方法,该方法可以访问在时间步长x_n处由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()


它完美地工作!

关于python - Scipy优化:获取函数以打印出其迭代,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42444045/

10-11 06:20