test_lbfgsb_hessinv.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. from __future__ import division, print_function, absolute_import
  2. import numpy as np
  3. from numpy.testing import assert_, assert_allclose
  4. import scipy.linalg
  5. from scipy.optimize import minimize
  6. def test_1():
  7. def f(x):
  8. return x**4, 4*x**3
  9. for gtol in [1e-8, 1e-12, 1e-20]:
  10. for maxcor in range(20, 35):
  11. result = minimize(fun=f, jac=True, method='L-BFGS-B', x0=20,
  12. options={'gtol': gtol, 'maxcor': maxcor})
  13. H1 = result.hess_inv(np.array([1])).reshape(1,1)
  14. H2 = result.hess_inv.todense()
  15. assert_allclose(H1, H2)
  16. def test_2():
  17. H0 = [[3, 0], [1, 2]]
  18. def f(x):
  19. return np.dot(x, np.dot(scipy.linalg.inv(H0), x))
  20. result1 = minimize(fun=f, method='L-BFGS-B', x0=[10, 20])
  21. result2 = minimize(fun=f, method='BFGS', x0=[10, 20])
  22. H1 = result1.hess_inv.todense()
  23. H2 = np.vstack((
  24. result1.hess_inv(np.array([1, 0])),
  25. result1.hess_inv(np.array([0, 1]))))
  26. assert_allclose(
  27. result1.hess_inv(np.array([1, 0]).reshape(2,1)).reshape(-1),
  28. result1.hess_inv(np.array([1, 0])))
  29. assert_allclose(H1, H2)
  30. assert_allclose(H1, result2.hess_inv, rtol=1e-2, atol=0.03)