This is one of the 100 recipes of the IPython Cookbook, the definitive guide to high-performance scientific computing and data science in Python.
import numpy as np
import scipy.optimize as opt
import matplotlib.pyplot as plt
%matplotlib inline
np.random.seed(3)
def f(x, a, b, c, d):
return a/(1. + np.exp(-c * (x-d))) + b
a, c = np.random.exponential(size=2)
b, d = np.random.randn(2)
n = 100
x = np.linspace(-10., 10., n)
y_model = f(x, a, b, c, d)
y = y_model + a * .2 * np.random.randn(n)
plt.figure(figsize=(6,4));
plt.plot(x, y_model, '--k');
plt.plot(x, y, 'o');
curve_fit
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, (a, b, c, d))
y_fit = f(x, a_, b_, c_, d_)
plt.figure(figsize=(6,4));
plt.plot(x, y_model, '--k');
plt.plot(x, y, 'o');
plt.plot(x, y_fit, '-');
The fitted sigmoid appears to be quite close from the original sigmoid used for data generation.
You'll find all the explanations, figures, references, and much more in the book (to be released later this summer).
IPython Cookbook, by Cyrille Rossant, Packt Publishing, 2014 (500 pages).