使用Python将Sigmoid函数(“ S”形曲线)拟合到数据

时间:2019-04-17 10:10:51

标签: python-3.x scipy curve-fitting sigmoid

我正在尝试将sigmoid函数拟合到我拥有的某些数据,但我不断得到:ValueError: Unable to determine number of fit parameters.

我的数据如下:

enter image description here

我的代码是:

from scipy.optimize import curve_fit

def sigmoid(x):
    return (1/(1+np.exp(-x)))

popt, pcov = curve_fit(sigmoid, xdata, ydata, method='dogbox')

然后我得到:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-5-78540a3a23df> in <module>
      2     return (1/(1+np.exp(-x)))
      3 
----> 4 popt, pcov = curve_fit(sigmoid, xdata, ydata, method='dogbox')

~\Anaconda3\lib\site-packages\scipy\optimize\minpack.py in curve_fit(f, xdata, ydata, p0, sigma, absolute_sigma, check_finite, bounds, method, jac, **kwargs)
    685         args, varargs, varkw, defaults = _getargspec(f)
    686         if len(args) < 2:
--> 687             raise ValueError("Unable to determine number of fit parameters.")
    688         n = len(args) - 1
    689     else:

ValueError: Unable to determine number of fit parameters.

我不确定为什么这不起作用,这似乎是微不足道的动作->将曲线拟合到某个点。所需的曲线如下所示:

enter image description here

对不起,图形。我是在PowerPoint中完成的...

如何找到最佳的S形(“ S”形)曲线?

更新

由于@Brenlla,我已将代码更改为:

def sigmoid(k,x,x0):
    return (1 / (1 + np.exp(-k*(x-x0))))

popt, pcov = curve_fit(sigmoid, xdata, ydata, method='dogbox')

现在我没有收到错误,但是曲线不是所希望的:

x = np.linspace(0, 1600, 1000)
y = sigmoid(x, *popt)

plt.plot(xdata, ydata, 'o', label='data')
plt.plot(x,y, label='fit')
plt.ylim(0, 1.3)
plt.legend(loc='best')

结果是:

enter image description here

如何改进它,使其更适合数据?

UPDATE2

代码现在为:

def sigmoid(x, L,x0, k, b):
    y = L / (1 + np.exp(-k*(x-x0)))+b

但是结果仍然是...

enter image description here

UPDATE3

在@Brenlla的大力帮助下,代码被修改为:

def sigmoid(x, L ,x0, k, b):
    y = L / (1 + np.exp(-k*(x-x0)))+b
    return (y)

p0 = [max(ydata), np.median(xdata),1,min(ydata)] # this is an mandatory initial guess

popt, pcov = curve_fit(sigmoid, xdata, ydata,p0, method='dogbox')

结果:

enter image description here

1 个答案:

答案 0 :(得分:2)

在@Brenlla的大力帮助下,代码被修改为:

def sigmoid(x, L ,x0, k, b):
    y = L / (1 + np.exp(-k*(x-x0)))+b
    return (y)

p0 = [max(ydata), np.median(xdata),1,min(ydata)] # this is an mandatory initial guess

popt, pcov = curve_fit(sigmoid, xdata, ydata,p0, method='dogbox')

结果:

enter image description here