Fitting data with python

From LPTMS Wiki
Revision as of 14:24, 20 October 2011 by Roux (talk | contribs) (Created page with "The basic syntax is the following: <source lang="py"> #!/usr/bin/python from scipy import optimize from numpy import array # your data as lists x = [0.0, 1.0, 2.0, 3.0] y = [1...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

The basic syntax is the following: <source lang="py">

  1. !/usr/bin/python

from scipy import optimize from numpy import array

  1. your data as lists

x = [0.0, 1.0, 2.0, 3.0] y = [1.0, 0.5, 0.0, -1.0]

  1. define a fitting function and the corresponding error function that must be minimized
  2. use the lambda shortcut or define standard functions with def fit():
  3. p is the list of parameters

fit = lambda p, x: p[0] + p[1]*(x) + p[2]*(x)**2 err = lambda p, x, y: fit(p,x) - y

  1. initial guess

p0 = [1.0,1.0,1.0]

  1. calls optimize.leastsq to find optimal parameters, converts lists into numpy.array on the fly

p, success = optimize.leastsq(err, p0, args=(array(x), array(y)), ftol=5e-9, xtol=5e-9)

  1. some info about convergence is in success and the optimized parameters in p

</source>