from math import sqrt
def linreg(xy):
"""
Summary
Linear regression of y = ax + b
Usage
real, real, real = linreg(list(xy))
Returns coefficients to the regression line "y=ax+b" from x[] and y[], and R^2 Value
given a list (or whatever) of (x, y) pairs.
From: http://www.answermysearches.com/how-to-do-a-simple-linear-regression-in-python/124/
"""
N = len(xy)
Sx = Sy = Sxx = Syy = Sxy = 0.0
for x, y in xy:
Sx = Sx + x
Sy = Sy + y
Sxx = Sxx + x*x
Syy = Syy + y*y
Sxy = Sxy + x*y
det = Sxx * N - Sx * Sx
a, b = (Sxy * N - Sy * Sx)/det, (Sxx * Sy - Sx * Sxy)/det
meanerror = residual = 0.0
for x, y in xy:
meanerror = meanerror + (y - Sy/N)**2
residual = residual + (y - a * x - b)**2
RR = 1 - residual/meanerror
ss = residual / (N-2)
Var_a, Var_b = ss * N / det, ss * Sxx / det
return a, b, RR