scipy 如何将curve_fit用于涉及大小写拆分的函数?

8nuwlpux  于 2022-12-13  发布在  其他
关注(0)|答案(2)|浏览(113)

我想将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用于涉及大小写拆分的函数,如上面的例子。

mkh04yzy

mkh04yzy1#

问题是x < 4不是一个布尔标量值,因为curve_fit会用np.ndarray x(你给定的x个数据点)来计算你的函数,而不是一个标量值。因此,x < 4会给你一个布尔值数组。
也就是说,您可以使用NumPy的矢量化操作来重写函数:

def slope_devided_by_cases(x,a,b):
    return (x < 4) * (a*x + b) + (x >= 4) * (4*a+b)

或者,您可以使用np.where作为if-else方法的矢量化替代方法:

def slope_devided_by_cases(x,a,b):
    return np.where(x < 4, a*x + b, 4+a+b)
xqnpmsa8

xqnpmsa82#

另一个有趣的方法是使用numpy的piecewise函数。

from matplotlib import pyplot as plt
from scipy.optimize import curve_fit
import numpy as np

def f(x, a, b):
    return np.piecewise(
        x, [x < 4, x >= 4], [lambda x_: a * x_ + b, lambda x_: 4 * a + b]
    )

data_x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
data_y = np.array([45, 46, 42, 36, 27, 23, 21, 13, 11])
coeff, cov = curve_fit(f, data_x, data_y)

y_fit = f(data_x, *coeff)
plt.plot(data_x, data_y, "o")
plt.plot(data_x, y_fit, "-")
plt.show()

这是优化的结果(也许可以选择一个更好的模型,但我不知道手头问题的所有细节,我甚至没有指定任何初始值,因为这个问题更多的是让代码工作)。

相关问题