使用scipy最小化也采用非变分参数的函数 [英] Using scipy to minimize a function that also takes non variational parameters
问题描述
我想使用scipy.optimize
模块来最小化功能.假设我的功能是f(x,a)
:
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
对于固定的a
,我想相对于x
最小化f(x,a)
.
For a fixed a
, I want to minimize f(x,a)
with respect to x
.
使用scipy
,我可以导入例如fmin
函数(我有一个旧版本:v.0.9.0),给出一个初始值x0
,然后进行优化(
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)
失败,因为f
接受两个参数,而fmin
仅传递一个参数(实际上,我什至还没有定义a
).如果我这样做:
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)
计算也将失败,因为"x未定义".但是,如果我定义x
,则没有可优化的变分参数.
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?
推荐答案
了解fmin
,并使用
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,))
这篇关于使用scipy最小化也采用非变分参数的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!