test_lbfgsb_hessinv.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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)
  30. def test_3():
  31. def todense_old_impl(self):
  32. s, y, n_corrs, rho = self.sk, self.yk, self.n_corrs, self.rho
  33. I_arr = np.eye(*self.shape, dtype=self.dtype)
  34. Hk = I_arr
  35. for i in range(n_corrs):
  36. A1 = I_arr - s[i][:, np.newaxis] * y[i][np.newaxis, :] * rho[i]
  37. A2 = I_arr - y[i][:, np.newaxis] * s[i][np.newaxis, :] * rho[i]
  38. Hk = np.dot(A1, np.dot(Hk, A2)) + (rho[i] * s[i][:, np.newaxis] *
  39. s[i][np.newaxis, :])
  40. return Hk
  41. H0 = [[3, 0], [1, 2]]
  42. def f(x):
  43. return np.dot(x, np.dot(scipy.linalg.inv(H0), x))
  44. result1 = minimize(fun=f, method='L-BFGS-B', x0=[10, 20])
  45. assert_allclose(result1.hess_inv.todense(), todense_old_impl(result1.hess_inv))