【发布时间】:2020-09-04 15:58:44
【问题描述】:
我正在尝试使用 scipy 中的 curve_fit 函数对一些数据进行建模。我有 5 组数据,它们将与不同的权重相加以拟合观察到的数据 y。
def model(kidx, c10,c20,c40,c80,c160):
mod = (c10*data['10'][kidx] +
c20*data['20'][kidx] +
c40*data['40'][kidx] +
c80*data['80'][kidx] +
c160*data['160'][kidx])
return mod
curve_fit(model, k, y)
data 是包含 numpy 数组的字典,k 是索引列表,y 是目标数据。当我运行这段代码时,它返回一个 IndexError:
IndexError Traceback (most recent call last)
<ipython-input-18-51aba3bc37c2> in <module>
----> 1 curve_fit(model, k, y)
~/.conda/envs/heinrich/lib/python3.7/site-packages/scipy/optimize/minpack.py in curve_fit(f, xdata, ydata, p0, sigma, absolute_sigma, check_finite, bounds, method, jac, **kwargs)
750 # Remove full_output from kwargs, otherwise we're passing it in twice.
751 return_full = kwargs.pop('full_output', False)
--> 752 res = leastsq(func, p0, Dfun=jac, full_output=1, **kwargs)
753 popt, pcov, infodict, errmsg, ier = res
754 cost = np.sum(infodict['fvec'] ** 2)
~/.conda/envs/heinrich/lib/python3.7/site-packages/scipy/optimize/minpack.py in leastsq(func, x0, args, Dfun, full_output, col_deriv, ftol, xtol, gtol, maxfev, epsfcn, factor, diag)
381 if not isinstance(args, tuple):
382 args = (args,)
--> 383 shape, dtype = _check_func('leastsq', 'func', func, x0, args, n)
384 m = shape[0]
385
~/.conda/envs/heinrich/lib/python3.7/site-packages/scipy/optimize/minpack.py in _check_func(checker, argname, thefunc, x0, args, numinputs, output_shape)
24 def _check_func(checker, argname, thefunc, x0, args, numinputs,
25 output_shape=None):
---> 26 res = atleast_1d(thefunc(*((x0[:numinputs],) + args)))
27 if (output_shape is not None) and (shape(res) != output_shape):
28 if (output_shape[0] != 1):
~/.conda/envs/heinrich/lib/python3.7/site-packages/scipy/optimize/minpack.py in func_wrapped(params)
456 if transform is None:
457 def func_wrapped(params):
--> 458 return func(xdata, *params) - ydata
459 elif transform.ndim == 1:
460 def func_wrapped(params):
<ipython-input-17-8bc44c07046b> in model(kidx, c10, c20, c40, c80, c160)
1 def model(kidx, c10,c20,c40,c80,c160):
----> 2 mod = c10*data['10'][kidx] + c20*data['20'][kidx] + c40*data['40'][kidx] + c80*data['80'][kidx] + c160*data['160'][kidx]
3 return mod
IndexError: arrays used as indices must be of integer (or boolean) type
这里发生了什么? k 是一个整数数组,它是唯一可以用作索引的数组。这些变量以前都没有在笔记本中使用过。
【问题讨论】:
-
在
model函数中添加print(kidx)行,这样您就可以清楚地知道fit传递给该函数的值是什么。当使用像这样的scipy函数时,请密切注意文档对您的函数的评价,以及它应该接受的参数。不要猜测。测试。
标签: python numpy scipy linear-regression