SciPy最小化:如何打印有限差分雅可比的值?

时间:2016-04-11 19:09:42

标签: python optimization scipy

有没有办法让scipy.optimize.minimize在每次迭代时打印估计渐变的值?我想将它与我正在计算的分析梯度的值进行比较。

1 个答案:

答案 0 :(得分:1)

您可以向callback提供scipy.optimize.minimize函数,该函数在每次迭代后调用,并结合各种方法在内部使用的函数进行数值近似(scipy.optimize.optimize._approx_fprime_helper)。以rosen函数为例:

import numpy as np
from scipy.optimize import rosen, rosen_der, minimize
from scipy.optimize.optimize import _approx_fprime_helper

def callback(x):
    print 'exact: ', rosen_der(x)
    print 'approx: ', _approx_fprime_helper(x, rosen, 1E-8)
    print '-----'

x0 = np.zeros(5)
res = minimize(rosen, x0, method='L-BFGS-B', callback=callback)

这会给你类似的东西:

exact:  [-2.11963396  1.84037029  1.84037037  2.00372223 -0.08167787]
approx:  [-2.11963398  1.84037128  1.84037137  2.00372323 -0.08167684]
-----
exact:  [-2.09674976  0.65207886  0.77546647  0.73540194  0.02017962]
approx:  [-2.0967498   0.65207981  0.77546742  0.73540298  0.02018057]
-----
exact:  [-1.89973856 -1.67615541 -0.88726966 -1.04665196  0.08082156]
approx:  [-1.8997385  -1.67615442 -0.88726866 -1.04665099  0.08082255]
-----
exact:  [ 0.71591999 -7.99959011 -2.81299766 -3.18692904  0.18447144]
approx:  [ 0.71592021 -7.99958908 -2.81299664 -3.18692805  0.18447244]
-----

如果您深入了解优化器源代码,您将看到_approx_fprime_helper被调用的位置。它的定义如下:

https://github.com/scipy/scipy/blob/master/scipy/optimize/optimize.py#L601

确保您将eps调用中定义的minimize值与传递给_approx_fprime_helper的内容相匹配。