Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
699 views
in Technique[技术] by (71.8m points)

python - Using scipy to minimize a function that also takes non variational parameters

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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,))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...