S-curve fitting in Python

Hi Python Community!

I am a bit new to Pyhton and need to do some curve fitting for S-curves. I have given data points for x and y and need to find a sigmoid function with parameters L, x0 and k that describes the data best, i.e. curve fitting. I found a code like this below:

import matplotlib.pyplot as plt
import numpy as np
from scipy.special import expit as logistic

x = np.arange(-6, 6.1, 0.1)
y = logistic(x) + np.random.normal(loc=0.0, scale=0.03, size=len(x))
fig, ax = plt.subplots(figsize=(15, 6))
_ = ax.plot(x, y)
_ = ax.set_title('Generated s-curve data with noise test')

from scipy.optimize import curve_fit
L_estimate = y.max()
x_0_estimate = np.median(x)
k_estimate = 1.0
p_0 = [L_estimate, x_0_estimate, k_estimate]
popt, pcov = curve_fit(logistic, x, y, p_0, method='dogbox')

However, when I test run it, it shows a TypeError:
TypeError: expit() takes from 1 to 2 positional arguments but 4 were given.

I do not really know what to do about that. And of course in the code so far it is using random data, but would insert my own data afterwards, if it runs smoothly.

Thanks for your help, maybe I am missing an important point.

Changing the name of the expit function to “logistic” doesn’t change the function. The curve_fit function requires the function you are trying to fit to accept additional parameters. But the expit function does not take any extra parameters so there is nothing to fit to.

The expit function only provides you with y = 1/(1+exp(-x)). As you can see there are no parameters that can be changed to fit to a curve.

At a guess, try using this instead of expit:

def func(x, a, b, c):
    return a/(b + exp(-c*x))

Warning: I am literally guessing here. I have never used scipy’s curve fitting so I don’t know if this will work or not.