Created
April 8, 2014 15:25
-
-
Save salmoni/10142282 to your computer and use it in GitHub Desktop.
Brief code to calculate line of best fit for a single vector ('y'). Assumes the 'x' variable is a simple range from 0 .. N-1. Returns the intercept, the slope, the correlation between x and y, and the residual (error). Doesn't use the lstsq function in numpy but the results are the same.
This file contains 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
import numpy | |
x = numpy.array(range(400)) | |
xm = x.mean() | |
xstd = x.std() | |
def fitline(y): | |
N = len(y) | |
x = numpy.array(range(N)) | |
ym = y.mean() | |
ystd = y.std() | |
xm = x.mean() | |
xstd = x.std() | |
r = numpy.corrcoef(x, y)[0,1] | |
b1 = r * (ystd / xstd) | |
b0 = ym - (b1 * xm) | |
resid = (y - numpy.array(x*b1)+b0) ** 2 | |
return b0, b1, r, resid.sum() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment