Created
February 16, 2017 00:44
-
-
Save marshareb/6316541a0243f4dc51016e81e08975a3 to your computer and use it in GitHub Desktop.
Preforms simple linear regression in 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
import warnings | |
#----------------------------------------------------------------------------------------------------------------------- | |
#power function | |
#python has one built in but the point of this program is to do unecessary things for practice | |
def power(x, pow): | |
if type(pow) != int and pow > 0: | |
warnings.warn("pow needs to be an integer value greater than 0") | |
if pow == 0: | |
return 1 | |
for i in range(pow-1): | |
x = x*x | |
return x | |
#----------------------------------------------------------------------------------------------------------------------- | |
#sum function | |
#python has one built in but the point of this program is to do unecessary things for practice | |
def ffsum(list): | |
x = 0 | |
for i in list: | |
try: | |
x+= i | |
except: | |
warnings.warn("you probably don't have just numeric values in the list") | |
return x | |
#----------------------------------------------------------------------------------------------------------------------- | |
#note here that x1, x2 denote the two lists that we will preform linear regression on | |
#we assume them to have the same size | |
def simple_linear_regression(x1, x2): | |
if len(x1) != len(x2): | |
warnings.warn("the lists are not the same size") | |
x1x2 = [] | |
x1sq = [] | |
x2sq = [] | |
for i in range(len(x1)): | |
x1x2.append(x1[i]*x2[i]) | |
x1sq.append(power(x1[i], 2)) | |
x2sq.append(power(x2[i], 2)) | |
#arbitrarily chose x1, could've used x2 as well | |
n = len(x1) | |
#Note we have to sloppily convert all of these values to float. Probably should find out a way to do it better. | |
a = ((float(ffsum(x2))*float(ffsum(x1sq)))-(float(ffsum(x1))*float(ffsum(x1x2))))/(float(n)*float(ffsum(x1sq))-float(power(ffsum(x1), 2))) | |
b = (float(n)*float(ffsum(x1x2))-float(ffsum(x1))*float(ffsum(x2)))/(float(n)*float(ffsum(x1sq))-float(power(ffsum(x1), 2))) | |
print('a: ' + str(a)) | |
print('b: ' + str(b)) | |
return a, b | |
#----------------------------------------------------------------------------------------------------------------------- | |
if __name__ == "__main__": | |
#test values | |
x = [43,21,25,42,57,59] | |
y= [99,65,79,75,87,81] | |
#expected: a ~ 65.1416 | |
#expected: b ~ .385225 | |
simple_linear_regression(x, y) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment