使用 Python 将 sigmoid 函数(“S"形曲线)拟合到数据 [英] Fit sigmoid function ("S" shape curve) to data using Python

查看:58
本文介绍了使用 Python 将 sigmoid 函数(“S"形曲线)拟合到数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 sigmoid 函数拟合到我拥有的一些数据,但我不断收到:ValueError:无法确定拟合参数的数量.

I'm trying to fit a sigmoid function to some data I have but I keep getting:ValueError: Unable to determine number of fit parameters.

我的数据如下所示:

我的代码是:

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')

~Anaconda3libsite-packagesscipyoptimizeminpack.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.

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

I'm not sure why this does not work, it seems like a trivial action--> fit a curve to some point. The desired curve would look like this:

抱歉,图片显示...我是在 PowerPoint 中完成的...

Sorry for the graphics.. I did it in PowerPoint...

如何找到最佳的 sigmoid(S"形)曲线?

How can I find the best sigmoid ("S" shape) curve?

更新

感谢@Brenlla,我已将代码更改为:

Thanks to @Brenlla I've changed my code to:

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

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

现在我没有收到错误,但曲线并不如预期:

Now I do not get an error, but the curve is not as desired:

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')

结果是:

我该如何改进它才能更好地拟合数据?

How can I improve it so it will fit the data better?

更新2

代码现在是:

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

但结果还是...

推荐答案

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

After great help from @Brenlla the code was modified to:

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')

结果:

这篇关于使用 Python 将 sigmoid 函数(“S"形曲线)拟合到数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆