DimKoim
DimKoim

Reputation: 1044

Optimization (with scipy.optimize.minimize) with multiple variables

I want to implement the Nelder-Mead optimization on an equation. But it does not contain only one variable, it contains multiple variables (one of them which is the unknown, and the others known.)

For instance at this example: http://docs.scipy.org/doc/scipy/reference/tutorial/optimize.html

If my rosen(x) was

def rosen(x,y):
...     """The Rosenbrock function"""
...     return sum(100.0*(x[1:]-x[:-1]**2.0)**y + (1-x[:-1])**2.0)

instead of this that is mentioned on the example, how could i optimise it? If i call

res = minimize(rosen, x0, method='nelder-mead',
...                options={'xtol': 1e-8, 'disp': True})

it says that needs two arguments if i call

res = minimize(rosen(y), x0, method='nelder-mead',
...                options={'xtol': 1e-8, 'disp': True})

with y already defined previously on the code, i get the same error. While if I call it

res = minimize(rosen(x,y), x0, method='nelder-mead',
...                options={'xtol': 1e-8, 'disp': True})

I get an error that x is not defined.

Upvotes: 0

Views: 9226

Answers (1)

Dietrich
Dietrich

Reputation: 5531

Passing arguments to the objects is done with parameter args. Optimizing rosen(x,2):

import numpy as np
from scipy.optimize import minimize

def rosen(x, y):
    """The Rosenbrock function"""
    return sum(100.0*(x[1:]-x[:-1]**2.0)**y + (1-x[:-1])**2.0)

x0 = np.array([1.3, 0.7, 0.8, 1.9, 1.2])

res = minimize(rosen, x0, args=(2,), method='nelder-mead',
               options={'xtol': 1e-8, 'disp': True})

Note that the variable x is a 5 dimensional vector, as you can see in the definition of the starting point x0, hence rosen(x,2) has five variables. If your you want to minimize rosen(x,y), define a objective function

def rosen2(zz):
    return rosen(zz[:5], zz[5])

Upvotes: 4

Related Questions