Package madrona :: Package analysistools :: Module utils
[hide private]

Source Code for Module madrona.analysistools.utils

 1  from math import sqrt 
2 -def linear_regression(X, Y):
3 """ 4 http://www.answermysearches.com/how-to-do-a-simple-linear-regression-in-python/124/ 5 Summary 6 Linear regression of y = ax + b 7 Usage 8 real, real, real = linreg(list, list) 9 a, b, r2 = linreg(list, list) 10 Returns coefficients to the regression line "y=ax+b" from x[] and y[], and R^2 Value 11 """ 12 if len(X) != len(Y): 13 raise ValueError('unequal length') 14 N = len(X) 15 Sx = Sy = Sxx = Syy = Sxy = 0.0 16 for x, y in map(None, X, Y): 17 Sx = Sx + x 18 Sy = Sy + y 19 Sxx = Sxx + x * x 20 Syy = Syy + y * y 21 Sxy = Sxy + x * y 22 det = Sxx * N - Sx * Sx 23 a, b = (Sxy * N - Sy * Sx) / det, (Sxx * Sy - Sx * Sxy) / det 24 meanerror = residual = 0.0 25 for x, y in map(None, X, Y): 26 meanerror = meanerror + (y - Sy / N) ** 2 27 residual = residual + (y - a * x - b) ** 2 28 RR = 1 - residual / meanerror 29 ss = residual / (N - 2) 30 Var_a, Var_b = ss * N / det, ss * Sxx / det 31 return a, b, RR
32