HennyKo
HennyKo

Reputation: 772

How to return best guess of scipy minimize, when when no solution was found?

During my optimization, scipy often does not find a solution and simply return my initial guess. I would rather use the best values found so far rather than my initial guess.

> results = optimize.minimize(optimize_me, x0, method='BFGS', jac=True)
> results.success
False
> results.x == x0
True

Like this optimize_me(x0) == results.fun. But I would prefer optimize_me(results.x)/results.fun to be the lowest value found, even when no solution was found.

Upvotes: 0

Views: 1075

Answers (1)

cmbfast
cmbfast

Reputation: 489

Here's a solution with callback

func = lambda x: np.cos(14.5 * x - 0.3) + (x + 0.2) * x
x0=[1.]

def print_fun(x):
    print("Current value: {}".format(x))

minimize (func, x0, method = 'BFGS', callback=print_fun)

This prints current value with each iteration as:

Current value: [1.05820172]
Current value: [1.09236336]
Current value: [1.09262207]
Current value: [1.09260106]

      fun: 0.4259196810917082
 hess_inv: array([[0.00477712]])
      jac: array([-1.2665987e-06])
  message: 'Optimization terminated successfully.'
     nfev: 16
      nit: 4
     njev: 8
   status: 0
  success: True
        x: array([1.09260106])

You can modify the print function to your liking. However, not all optimization routine supports callback.

Upvotes: 1

Related Questions