To obtain the iteration data from Scipy "SLSQP" solver

Viewed 144

I want to obtain the iteration information from the Scipy solver "SLSQP". I developed a code using a callback function as described below.


from scipy.optimize import minimize, rosen, rosen_der

def callback(xk, step=[0]):
      print(step[0], xk[0] )
      step[0] += 1

x0 = [1.3, 0.7, 0.8, 1.9, 1.2]
res = minimize(rosen, x0, callback=callback, method='SLSQP',
    options={'ftol': 1e-6, 'disp': True})

And I got the solver output as

0 -514.1000091552735
1 -135.7415473476321
2 -17.549744746578245
3 17.564262441411472
4 -1.5602312826344646
5 1.0079282528485665
6 0.9069490399784312
7 0.8943984770283425

But, I want to get the values of function and both the decision variables for each iteration. How can I get that?

How would I grab these information into a Python list?

Can someone please help me?

Thank you very much in advance.

1 Answers

Use a wrapper function:

def track(f, out_values=None, out_args=None, out_kwargs=None):
    def wrapped(*args, **kwargs):
        if out_args is not None: out_args.append(args)
        if out_kwargs is not None: out_kwargs.append(kwargs)
        val = f(*args, **kwargs)
        if out_values is not None: out_values.append(val)
        return val
    return wrapped

Then:

>>> vars, vals = [], []
>>> x0 = [1.3, 0.7, 0.8, 1.9, 1.2]
>>> res = minimize(track(rosen, vals, vars), x0, method='SLSQP',
...    options={'ftol': 1e-6, 'disp': True})
>>> vals[:5]
[848.22, 848.2200076800586, 848.2199957472086, 848.2199949097634, 848.2200310748821
>>> vars[1]
(array([1.30000001, 0.7       , 0.8       , 1.9       , 1.2       ]),)
Related