简而言之:curve_fit试图在扩展数据数组上计算目标函数,但是quad不能接受向量参数。你需要通过输入数组的列表理解来定义你的目标函数。在
让我们想出一个最少可重复的例子:In [33]: xdata = np.linspace(0, 3, 11)
In [34]: ydata = xdata**3
In [35]: def integr(x):
...: return quad(lambda t: t**2, 0, x)[0]
...:
In [36]: def func(x, a):
...: return integr(x) * a
...:
In [37]: curve_fit(func, xdata, ydata)
-
ValueError Traceback (most recent call last)
in ()
> 1 curve_fit(func, xdata, ydata)
[... removed for clarity ...]
~/virtualenvs/py35/lib/python3.5/site-packages/scipy/integrate/quadpack.py in _quad(func, a, b, args, full_output, epsabs, epsrel, limit, points)
370 def _quad(func,a,b,args,full_output,epsabs,epsrel,limit,points):
371 infbounds = 0
> 372 if (b != Inf and a != -Inf):
373 pass # standard integration
374 elif (b == Inf and a != -Inf):
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
这正是你所看到的错误。好的,错误来自quad,它试图计算func(xdata, a),最后归结为integr(xdata),但这不起作用。(我是怎么发现的?我将import pdb; pdf.set_trace()放在func函数中,并在调试器中进行了查找)。在
然后,让目标函数handle数组参数:
^{pr2}$