[英]How to correctly use fminsearch in Python?
I'm trying to translate a part of my matlab code in python. 我正在尝试在python中翻译我的matlab代码的一部分。 Actually I'm looking for how to translate
fminsearch
and I found it on this website with this example : 其实我正在寻找如何翻译
fminsearch
,我在这个网站上找到了这个例子:
import scipy.optimize
banana = lambda x: 100*(x[1]-x[0]**2)**2+(1-x[0])**2
xopt = scipy.optimize.fmin(func=banana, x0=[-1.2,1])
My first question is how to return also the value of fmin
? 我的第一个问题是如何返回
fmin
的值?
And in my code when I type : 在我键入的代码中:
banana = lambda X: diff_norm(X, abst0, ord0);
Xu = scipy.optimize.fmin(func=banana, X)
Python answered me : Python回答我:
Xu = scipy.optimize.fmin(func=banana, X)
SyntaxError: non-keyword arg after keyword arg
I don't understand why Python told me that because what i want to do is to minimize the function diff_norm
changing the values of X
, i precise X
is an array of length 10. 我不明白为什么Python告诉我,因为我想要做的是最小化函数
diff_norm
改变X
的值,我精确X
是一个长度为10的数组。
Thank you very much for your help ! 非常感谢您的帮助 !
Python told you that because in Python, keyword arguments always follow non keyword (ie positional) arguments (keyword args have a name assigned to them, as in func
in the fmin
call). Python告诉你,因为在Python中,关键字参数总是遵循非关键字(即位置)参数(关键字args具有分配给它们的名称,如
fmin
调用中的func
)。 Your function call should look like: 您的函数调用应如下所示:
Xu = scipy.optimize.fmin(func=banana, x0=X)
in order to comply with Python's calling conventions . 为了符合Python的调用约定 。 Alternatively, and, according to the function definition of
fmin
, you could only supply positional arguments for these two first arguments: 或者,根据
fmin
的函数定义 ,您只能为这两个第一个参数提供位置参数:
Xu = scipy.optimize.fmin(banana, X)
this will return the values that minimize the function, so, just call the function providing these arguments: 这将返回最小化函数的值,因此,只需调用提供这些参数的函数:
minval = banana(Xu)
Alternatively you could call fmin
with full_output = True
and get a tuple of elements back, the second element of that tuple is the minimum value: 或者你可以用
full_output = True
调用fmin
并返回一个元组元组,该元组的第二个元素是最小值:
_, minval, *_ = scipy.optimize.fmin(banana, X, full_output=True)
Now minval
contains your full output. 现在
minval
包含您的完整输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.