简体   繁体   English

Python-Scipy fmin,为fmin提供参数

[英]Python - scipy fmin, giving the arguments to fmin

I'm a bit of a newbie in Python. 我是Python的新手。 I'm writing a little piece of code in order to find the minimum of a function: 我正在编写一些代码,以查找功能的最小值:

import os,sys,matplotlib,pylab
import numpy as np
from scipy.optimize import fmin

par = [2., 0.5, 0.008]
x1 = 0.4
f2_2 = lambda x, param: param[0] * x**2 + param[1] * x + param[2]
xmin = fmin(f2_2,x1,args = (par))

print xmin

it should be very simple, however I am getting this error: 它应该很简单,但是我遇到了这个错误:

"Traceback (most recent call last):

  File "prova.fmin.py", line 9, in <module>

 xmin = fmin(f2_2,x1,args = (par))

  File "/usr/lib/python2.7/dist-packages/scipy/optimize/optimize.py", line 257, in fmin

 fsim[0] = func(x0)

  File "/usr/lib/python2.7/dist-packages/scipy/optimize/optimize.py", line 176, in function_wrapper

 return function(x, *args)

TypeError: <lambda>() takes exactly 2 arguments (4 given)"

Could someone help me in understanding this please? 有人可以帮我理解这一点吗?

I just tried this out. 我只是尝试了一下。 Looks like you need to say (par,) and not just (par) . 看起来您需要说(par,)而不仅仅是(par) Note that (par,) is a tuple, with the variable par as a single element, whereas (par) just evaluates to par : no tuple. 请注意, (par,)是一个元组,变量par是一个元素,而(par)仅求值par :没有元组。 The " args " keyword of fmin expects to find a tuple, not par , which in this case is a list. fmin的“ args ”关键字期望找到一个元组,而不是par ,在这种情况下为列表。

Edit: Well, actually, it would seem that args doesn't mind receiving a list either. 编辑:嗯,实际上,似乎args也不介意接收列表。 But then, inside of fmin , when the function f2_2 is called, args is unpacked , meaning its contents are now passed as arguments to f2_2 . 但是然后,在fmin内部,当调用函数f2_2时, args解压缩 ,这意味着它的内容现在作为参数传递给f2_2 This means that f2_2 ends up getting four arguments, viz. 这意味着f2_2最终得到四个参数,即。 x , 2 , 0.5 and 0.008 in this case, as opposed to getting just the two arguments x and [2, 0.5, 0.008] . x20.50.008在此情况下,相对于获取只是两个参数x[2, 0.5, 0.008]

您需要定义lambda函数以接受更多参数,如下所示:

f2_2 = lambda x, *param: param[0] * x**2 + param[1] * x + param[2]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM