SHARE
TWEET

Untitled

a guest Jul 22nd, 2019 64 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import numpy as np
  2.  
  3.  
  4. def ternary_search(a, b, x, func, grad, H):
  5.     while b - a > 1e-3:
  6.         c = a + (b - a) / 3
  7.         d = a + (b - a) / 3 * 2
  8.         if func(x - c * H @ grad(x)) >= func(x - d * H @ grad(x)):
  9.             a = c
  10.         else:
  11.             b = d
  12.     return (b + a) / 2
  13.  
  14.  
  15. def bfgs(x0, grad, func, step):
  16.     xk = x0.copy()
  17.     n = xk.shape[0]
  18.     H = np.eye(n)
  19.     res = [func(xk)]
  20.     for i in range(1, step):
  21.         hk = ternary_search(0.0000001, 1, xk, func, grad, H)
  22.         x_last = xk.copy()
  23.         xk = xk - hk * H @ grad(xk)
  24.         yk = grad(xk) - grad(x_last)
  25.         delta = xk - x_last
  26.         Bk = 1 + (yk @ delta) / ((H @ yk) @ yk)
  27.         H = H + (H * yk * delta.T + delta * yk.T * H) / ((H @ yk) @ yk)
  28.         H -= Bk * ((H * yk * yk.T * H) / ((H @ yk) @ yk))
  29.         res.append(func(xk))
  30.     return xk, res
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top