Data modeling and fitting with Scipy

Definition

Linear regression

In [1]:
%matplotlib inline
from scipy.optimize import curve_fit
import numpy as np
import matplotlib.pyplot as plt
In [2]:
def f(x, a, b):
    return a * x + b

x = np.arange(-3., 3., 0.1)
y = f(x, 1., 2.)

yn = y + 0.9 * np.random.normal(size=x.shape[0])

popt, pcov = curve_fit(f, x, yn)

print(popt)
print(pcov)
[ 0.96591188  1.79223637]
[[ 0.00372482  0.00018624]
 [ 0.00018624  0.01118068]]
In [3]:
plt.title('Fitting Example')
plt.plot(x, y,'g.--')
plt.plot(x, yn,'k.')
plt.plot(x, f(x, *popt),'r.-')
plt.legend(['original','plus noise', 'fit'])

plt.show()
In [4]: