# [SciPy-User] Sigmoid Curve Fitting

Warren Weckesser warren.weckesser@enthought....
Tue Sep 21 13:36:57 CDT 2010

```  On 9/21/10 1:30 PM, Chris Spencer wrote:
> Right, I noticed that negating k should theoretically have the same
> effect. However, when I reversed your sample data (i.e. ydata =
> ydata[::-1]), I was surprised to find that curve_fit gives me
> f(x)=0.92 instead of a proper sigmoid curve.

Ah, in that case, it can help to give curve_fit a better initial guess
for the parameters.  For example, if I use

popt, pcov = curve_fit(sigmoid, xdata, ydata, p0=(1.0, -1.0, 1.0, 0.0))

with the original function, it works as expected.

Warren

> to work around this problem.
>
> Regards,
> Chris
>
> On Tue, Sep 21, 2010 at 2:21 PM, Warren Weckesser
> <warren.weckesser@enthought.com>  wrote:
>> On 9/21/10 1:04 PM, Chris Spencer wrote:
>>> I found this modification allows for the inversion of the estimated
>>> sigmoid curve:
>>>
>>> def sigmoid(x, x0, k, a, c, d):
>>>       y = 1 / (1 + np.exp(-k*(x-x0)))
>>>       y = (1 - y)*(1 - d) + y*d
>>>       y = a * y + c
>>>       return y
>>>
>>
>> A negative value of k "reverses" the sigmoid shape, so you shouldn't
>> have to define a new function.  If you prefer to have k be positive, you
>> could use
>>
>> def sigmoid(x, x0, k, a, c):
>>      y = a / (1 + np.exp(k*(x-x0))) + c
>>      return y
>>
>> (I changed "-k" to "k".)
>>
>>
>> Warren
>>
>>> Regards,
>>> Chris
>>>
>>> On Tue, Sep 21, 2010 at 1:02 PM, Chris Spencer<chrisspen@gmail.com>    wrote:
>>>> On Tue, Sep 21, 2010 at 12:16 PM, Warren Weckesser
>>>> <warren.weckesser@enthought.com>    wrote:
>>>>> The following is a variation that includes more parameters in the family
>>>>> of sigmoid functions.  But bear in mind, I chose this family of
>>>>> functions just as a demonstration of curve_fit.  I don't know if it
>>>>> makes sense to use this family for your data.  The appropriate family to
>>>>> use depends on the nature of the data.
>>>> I see what you mean. That modification only fits a low-to-high
>>>> sigmoid, but that's close enough for me to adapt by reversing my data
>>>> set. Thank you for the excellent example.
>>>>
>>>> Regards,
>>>> Chris
>>>>
>>> _______________________________________________
>>> SciPy-User mailing list
>>> SciPy-User@scipy.org
>>> http://mail.scipy.org/mailman/listinfo/scipy-user
>> _______________________________________________
>> SciPy-User mailing list
>> SciPy-User@scipy.org
>> http://mail.scipy.org/mailman/listinfo/scipy-user
>>
> _______________________________________________
> SciPy-User mailing list
> SciPy-User@scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user

```