Last active
August 29, 2015 14:02
-
-
Save astrolitterbox/1c1413d8f259d5937e0d to your computer and use it in GitHub Desktop.
A minimal working example of fitting your model to data using SciPy.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# A minimal working example of fitting your model to data using SciPy. | |
# I rewrote the Cookbook example (http://wiki.scipy.org/Cookbook/FittingData) for a simpler case | |
# and simpler syntax. | |
from __future__ import division | |
from pylab import * | |
from scipy import * | |
import numpy as np | |
from scipy import optimize | |
def fitfunc(x, p): | |
print x.shape, 'x' | |
ret = p[0]*x+p[1] # Model | |
return ret | |
def errfunc(p, x, y, yerr): | |
print p, 'params' | |
ret = (y - fitfunc(x, p)) / yerr# Distance b/ween model and data -- Chi (not squared, squaring and summing up are done by SciPy) | |
return ret | |
# Generate data points | |
num_points = 150 | |
x = linspace(5., 8., num_points) | |
y = 0.8*x + 12 | |
yerr = 0.2*np.ones((x.shape)) | |
p0 = [0.8, 0.] # Initial guess for the parameters | |
p1, success = optimize.leastsq(errfunc, p0[:], args=(x, y, yerr)) | |
scatter(x, y, c="r", label='data') # Plot of the data and the fit | |
plot(x, fitfunc(x, p1), c='g', label="fit", zorder=100) | |
errorbar(x, y, yerr=yerr, c='k') | |
legend() | |
show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment