Bill Harber - 2 months ago 16

Python Question

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

`fminsearch`

`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

`fmin`

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

`diff_norm`

`X`

`X`

Thank you very much for your help !

Answer

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.

Source (Stackoverflow)

Comments