Created
October 9, 2013 14:07
-
-
Save jaganadhg/6901893 to your computer and use it in GitHub Desktop.
Simple linier regression with Python
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
{ | |
"metadata": { | |
"name": "Simple linier regression with Python" | |
}, | |
"nbformat": 3, | |
"nbformat_minor": 0, | |
"worksheets": [ | |
{ | |
"cells": [ | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"#Example from http://www.answermysearches.com/how-to-do-a-simple-linear-regression-in-python/124/\n", | |
"from math import sqrt\n", | |
"def linreg(X, Y):\n", | |
" \"\"\"\n", | |
" Summary\n", | |
" Linear regression of y = ax + b\n", | |
" Usage\n", | |
" real, real, real = linreg(list, list)\n", | |
" Returns coefficients to the regression line \"y=ax+b\" from x[] and y[], and R^2 Value\n", | |
" \"\"\"\n", | |
" if len(X) != len(Y): raise ValueError, 'unequal length'\n", | |
" N = len(X)\n", | |
" Sx = Sy = Sxx = Syy = Sxy = 0.0\n", | |
" for x, y in map(None, X, Y):\n", | |
" Sx = Sx + x\n", | |
" Sy = Sy + y\n", | |
" Sxx = Sxx + x*x\n", | |
" Syy = Syy + y*y\n", | |
" Sxy = Sxy + x*y\n", | |
" det = Sxx * N - Sx * Sx\n", | |
" a, b = (Sxy * N - Sy * Sx)/det, (Sxx * Sy - Sx * Sxy)/det\n", | |
" meanerror = residual = 0.0\n", | |
" for x, y in map(None, X, Y):\n", | |
" meanerror = meanerror + (y - Sy/N)**2\n", | |
" residual = residual + (y - a * x - b)**2\n", | |
" RR = 1 - residual/meanerror\n", | |
" ss = residual / (N-2)\n", | |
" Var_a, Var_b = ss * N / det, ss * Sxx / det\n", | |
" #print \"y=ax+b\"\n", | |
" #print \"N= %d\" % N\n", | |
" #print \"a= %g \\\\pm t_{%d;\\\\alpha/2} %g\" % (a, N-2, sqrt(Var_a))\n", | |
" #print \"b= %g \\\\pm t_{%d;\\\\alpha/2} %g\" % (b, N-2, sqrt(Var_b))\n", | |
" #print \"R^2= %g\" % RR\n", | |
" #print \"s^2= %g\" % ss\n", | |
" return a, b, RR\n", | |
"\n", | |
"if __name__=='__main__':\n", | |
" #testing\n", | |
" X=[1,2,3,4]\n", | |
" Y=[357.14,53.57,48.78,10.48]\n", | |
" print linreg(X,Y)\n", | |
" #should be:\n", | |
" #Slope\tY-Int\tR\n", | |
" #-104.477\t378.685\t0.702499064" | |
], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"output_type": "stream", | |
"stream": "stdout", | |
"text": [ | |
"(-104.47700000000005, 378.68500000000006, 0.7024990637134721)\n" | |
] | |
} | |
], | |
"prompt_number": 1 | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [] | |
} | |
], | |
"metadata": {} | |
} | |
] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment