我想将curve_fit
用于涉及大小写拆分的函数。
但是python会抛出错误。curve_fit
不支持这样的函数?还是函数定义有问题?
示例)
from scipy.optimize import curve_fit
import numpy as np
def slope_devided_by_cases(x,a,b):
if x < 4:
return a*x + b
else:
return 4*a + b
data_x = [1,2,3,4,5,6,7,8,9] # x
data_y = [45,46,42,36,27,23,21,13,11] # y
coef, cov = curve_fit(slope_devided_by_cases, data_x, data_y)
错误)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
C:\Users\Lisa~1\AppData\Local\Temp/ipykernel_1516/1012358816.py in <module>
10 data_x = [1,2,3,4,5,6,7,8,9] # x
11 data_y = [45,46,42,36,27,23,21,13,11] # y
---> 12 coef, cov = curve_fit(slope_devided_by_cases, data_x, data_y)
~\anaconda3\lib\site-packages\scipy\optimize\minpack.py in curve_fit(f, xdata, ydata, p0, sigma, absolute_sigma, check_finite, bounds, method, jac, **kwargs)
787 # Remove full_output from kwargs, otherwise we're passing it in twice.
788 return_full = kwargs.pop('full_output', False)
--> 789 res = leastsq(func, p0, Dfun=jac, full_output=1, **kwargs)
790 popt, pcov, infodict, errmsg, ier = res
791 ysize = len(infodict['fvec'])
~\anaconda3\lib\site-packages\scipy\optimize\minpack.py in leastsq(func, x0, args, Dfun, full_output, col_deriv, ftol, xtol, gtol, maxfev, epsfcn, factor, diag)
408 if not isinstance(args, tuple):
409 args = (args,)
--> 410 shape, dtype = _check_func('leastsq', 'func', func, x0, args, n)
411 m = shape[0]
412
~\anaconda3\lib\site-packages\scipy\optimize\minpack.py in _check_func(checker, argname, thefunc, x0, args, numinputs, output_shape)
22 def _check_func(checker, argname, thefunc, x0, args, numinputs,
23 output_shape=None):
---> 24 res = atleast_1d(thefunc(*((x0[:numinputs],) + args)))
25 if (output_shape is not None) and (shape(res) != output_shape):
26 if (output_shape[0] != 1):
~\anaconda3\lib\site-packages\scipy\optimize\minpack.py in func_wrapped(params)
483 if transform is None:
484 def func_wrapped(params):
--> 485 return func(xdata, *params) - ydata
486 elif transform.ndim == 1:
487 def func_wrapped(params):
C:\Users\Lisa~1\AppData\Local\Temp/ipykernel_1516/1012358816.py in slope_devided_by_cases(x, a, b)
3
4 def slope_devided_by_cases(x,a,b):
----> 5 if x < 4:
6 return a*x + b
7 else:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
我想把curve_fit
用于涉及大小写拆分的函数,如上面的例子。
2条答案
按热度按时间mkh04yzy1#
问题是
x < 4
不是一个布尔标量值,因为curve_fit
会用np.ndarrayx
(你给定的x个数据点)来计算你的函数,而不是一个标量值。因此,x < 4
会给你一个布尔值数组。也就是说,您可以使用NumPy的矢量化操作来重写函数:
或者,您可以使用
np.where
作为if-else方法的矢量化替代方法:xqnpmsa82#
另一个有趣的方法是使用numpy的
piecewise
函数。这是优化的结果(也许可以选择一个更好的模型,但我不知道手头问题的所有细节,我甚至没有指定任何初始值,因为这个问题更多的是让代码工作)。