I want to use the scipy.optimize module to minimize a function. Let's say my function is f(x,a):
def f(x,a):
return a*x**2
For a fixed a, I want to minimize f(x,a) with respect to x.
With scipy I can import for example the fmin function (I have an old scipy: v.0.9.0), give an initial value x0 and then optimize (documentation):
from scipy.optimize import fmin
x0 = [1]
xopt = fmin(f, x0, xtol=1e-8)
which fails because f takes two arguments and fmin is passing only one (actually, I haven't even defined a yet). If I do:
from scipy.optimize import fmin
x0 = [1]
a = 1
xopt = fmin(f(x,a), x0, xtol=1e-8)
the calculation will also fail because "x is not defined". However, if I define x then there is no variational parameter to optimize.
How do I allow non-variational parameters to be used as function arguments here?
Read about the args argument to fmin in its docstring, and use
a = 1
x0 = 1
xopt = fmin(f, x0, xtol=1e-8, args=(a,))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With