Skip to content

Instantly share code, notes, and snippets.

@volf52
Created September 5, 2017 09:06
Show Gist options
  • Save volf52/c684adf543383969ce52572aba6c0ccf to your computer and use it in GitHub Desktop.
Save volf52/c684adf543383969ce52572aba6c0ccf to your computer and use it in GitHub Desktop.
Least Square Regression Line - Python
n = 5 # take input for total lines
X = []
Y = []
for _ in xrange(n):
x,y = map(int, raw_input().strip().split(' '))
X.append(x)
Y.append(y)
# input is done
x_sum = sum(X)
y_sum = sum(Y)
x_mean = x_sum / len(X)
y_mean = y_sum / len(Y)
x_sq_sum = sum([x**2 for x in X])
xy_sum = sum([x*y for x,y in zip(X,Y)])
b = ((n*xy_sum) - (x_sum * y_sum)) / (((n * x_sq_sum) - (x_sum ** 2)) * 1.0)
a = y_mean - (b * x_mean)
print "Y = %.3f + %.3f * X" % (round(a, 3), round(b, 3))
from sklearn import linear_model
import numpy as np
n = 5 # take input for total lines
X = []
Y = []
for _ in xrange(n):
x,y = map(int, raw_input().strip().split(' '))
X.append(x)
Y.append(y)
x = np.asarray(X).reshape(-1, 1)
lm = linear_model.LinearRegression()
lm.fit(x, Y)
a = (lm.intercept_)
b = (lm.coef_[0])
print "Y = %.3f + %.3f * X" % (round(a, 3), round(b, 3))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment