Bill Harber Bill Harber - 1 year ago 244
Python Question

How to correctly use fminsearch in Python?

I'm trying to translate a part of my matlab code in python. Actually I'm looking for how to translate

and I found it on this website with this example :

import scipy.optimize

banana = lambda x: 100*(x[1]-x[0]**2)**2+(1-x[0])**2
xopt = scipy.optimize.fmin(func=banana, x0=[-1.2,1])

My first question is how to return also the value of

And in my code when I type :

banana = lambda X: diff_norm(X, abst0, ord0);
Xu = scipy.optimize.fmin(func=banana, X)

Python answered me :

Xu = scipy.optimize.fmin(func=banana, X)
SyntaxError: non-keyword arg after keyword arg

I don't understand why Python told me that because what i want to do is to minimize the function
changing the values of
, i precise
is an array of length 10.

Thank you very much for your help !

Jim Jim
Answer Source

Python told you that because in Python, keyword arguments always follow non keyword (i.e positional) arguments (keyword args have a name assigned to them, as in func in the fmin call). Your function call should look like:

Xu = scipy.optimize.fmin(func=banana, x0=X)

in order to comply with Python's calling conventions. Alternatively, and, according to the function definition of fmin, you could only supply positional arguments for these two first arguments:

Xu = scipy.optimize.fmin(banana, X)

this will return the values that minimize the function, so, just call the function providing these arguments:

minval = banana(Xu)

Alternatively you could call fmin with full_output = True and get a tuple of elements back, the second element of that tuple is the minimum value:

_, minval, *_ = scipy.optimize.fmin(banana, X, full_output=True)

Now minval contains your full output.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download