test_lbfgsb_hessinv.py 1.1 KB

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