Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
linear regression with 1 variable in python
testset = [
[1, 4],
[2, 8],
[3, 12],
[4, 16]
]
theta0 = 0
theta1 = 0
learningrate = 0.01
# h of theta(x) = theta0 + theta1 * x
def hypo(something):
global theta0
global theta1
return theta0 + (theta1 * something)
def ms1(testset):
s = 0
for element in testset:
s = s + (hypo(element[0]) - element[1])
return 1.0/len(testset) * s
def ms2(testset):
s = 0
for element in testset:
s = s + ((hypo(element[0]) - element[1]) * element[0])
return 1.0/len(testset) * s
def compute(testset):
global theta0
global theta1
print "Starting with theta0 = %s" % theta0
print "Starting with theta1 = %s" % theta1
prev = [0, 0]
while(True):
new_theta0 = theta0 - (learningrate * ms1(testset))
new_theta1 = theta1 - (learningrate * ms2(testset))
theta0 = new_theta0
theta1 = new_theta1
#print "%s - %s" % (theta0, theta1)
if theta0 == prev[0] and theta1 == prev[1]:
return prev
prev = [theta0, theta1]
compute(testset)
assert round(hypo(5)) == 20.0
assert round(hypo(20)) == 80.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment