This is an example of a better way to work on and display numerical python code.

Here's the input script used to generate this document.


Logistic curve fitting example

Example is taken mostly from here.

We define a logistic function with four parameters:

\[f_{a,b,c,d}(x) = \frac{a}{1 + \exp\left(-c (x-d)\right)} + b\]

def f(x, a, b, c, d):
    return a / (1. + np.exp(-c * (x - d))) + b
The equation we'll try and fit

Define some random parameters:

a, c = np.random.exponential(size=2)
b, d = np.random.randn(2)

which are:

Now, we generate random data points by using the sigmoid function and adding a bit of noise:

n = 100
x = np.linspace(-10, 10, n)
y_model = f(x, a, b, c, d)
y = y_model + a * 0.2 * np.random.randn(n)

Plot that to see how it looks:

We now assume that we only have access to the data points and not the underlying generative function. These points could have been obtained during an experiment.

By looking at the data, the points appear to approximately follow a sigmoid, so we may want to try to fit such a curve to the points. That's what curve fitting is about.

SciPy's curve_fit() function allows us to fit a curve defined by an arbitrary Python function to the data:

(a_, b_, c_, d_), _ = opt.curve_fit(f, x, y)

And use those parameters to estimate our underlying curve

y_fit = f(x, a_, b_, c_, d_)

we can also manually compare our initial parameters with with those from curve_fit():