Minimize function with parameters Minimize function with parameters python python

Minimize function with parameters


You can specify additional arguments in args

from scipy.optimize import minimize minimize(f, x0, args=(a, b, c))


This is a straightforward question and answer about using minimize. In case other users need something more concrete, here's a simple example.

A generalized quadratic equation:

In [282]: def fun(x, a,b,c):     ...:     return a*x**2 + b*x + cIn [283]: optimize.minimize(fun, 10, args=(1,0,0))Out[283]:       fun: 1.7161984122524196e-15 hess_inv: array([[ 0.50000001]])      jac: array([ -6.79528891e-08])  message: 'Optimization terminated successfully.'     nfev: 15      nit: 4     njev: 5   status: 0  success: True        x: array([ -4.14270251e-08])In [284]: optimize.minimize(fun, 10, args=(1,1,1))Out[284]:       fun: 0.7500000000000221 hess_inv: array([[ 0.49999999]])      jac: array([  3.12924385e-07])  message: 'Optimization terminated successfully.'     nfev: 12      nit: 2     njev: 4   status: 0  success: True        x: array([-0.49999985])

The function could take arrays as input as well, but still needs to return a single (scalar) value:

In [289]: optimize.minimize(fun, [10,10,10], args=(np.array([1,2,3]), 1, 1))Out[289]:       fun: 2.541666666667115 hess_inv: array([[ 0.50021475, -0.00126004,  0.00061239],       [-0.00126004,  0.25822101, -0.00259327],       [ 0.00061239, -0.00259327,  0.16946887]])      jac: array([ -8.94069672e-08,   4.47034836e-07,  -2.20537186e-06])  message: 'Optimization terminated successfully.'     nfev: 55      nit: 9     njev: 11   status: 0  success: True        x: array([-0.50000006, -0.2499999 , -0.16666704])In [286]: def fun(x, a,b,c): ...:     return (a*x**2 + b*x + c).sum()

It's a good idea to make sure the function runs with the proposed x0 and args, e.g.

In [291]: fun(np.array([10,10,10]), np.array([1,2,3]), 1, 1)Out[291]: 633

If you can't call the objective function, or are confused as to how its arguments work, minimize isn't a magic bullet. This minimization is only as good as your understanding of the objective function.