Saturday, October 1, 2016

Curve-Fitting with Python

The curve_fit function from scipy.optimize offers a simple interface to perform unconstrained non-linear least-squares fitting.

It uses Levenberg-Marquardt, and provides a simple interface to the more general least-squares fitting routine leastsq.



Procedure


  • Given a bunch of data (\(x_i, f_i\)) and a fitting function \(f(x; a_1, a_2)\), where the \(a_i\) are the parameters to be fit, and \(x\) is the independent variable
  • Convert the math function to a python function. The first argument should be the independent variable; the parameters to be fit should follow
  • Import the function curve_fit from scipy.optimize
  • Call this routine with the function and data. It returns the best-fit and covariance matrix.

Example


Define function:

def f(x, a1, a2):
    f = np.exp(a1*x) * np.sin(a2*x)
    return f

Generate noisy data with a1 = -1 and a2  = 0.5:

xi = np.linspace(0,5.)
fi = f(xi, -1, 0.5) + np.random.normal(0, 0.005, len(xi))

Perform the fit:

from scipy.optimize import curve_fit
popt, pcov = curve_fit(f, xi, fi)

popt = array([-1.00109124,  0.49108962])

Plot:

plt.plot(xi,fi,'o')
plt.plot(xi, f(xi, popt[0], popt[1]))




No comments: