Guide to Linear Regressions in Python

import numpy as np
import matplotlib as plt
# create independent and dependent variables
# independent
X = np.array([1,2,3,4,5,6,7,8,9,10], dtype=np.float64)
# dependent
Y = np.array([6,6,8,10,10,12,12,15,13,16], dtype=np.float64)
plt.scatter(X,Y)#################
Returns:
See figure below.
Scatter plot of data
def calc_slope(X,Y):

# calculate the slope using formula above
m = (((np.mean(X)*np.mean(Y)) - np.mean(X*Y)) /
((np.mean(X)**2) - np.mean(X*X)))

return m
def best_fit(X,Y):

# find intercept by solving slope-intercept equation
m = calc_slope(X,Y)
b = np.mean(Y) — m*np.mean(X)

return m, b
def reg_line (m, b, X):

return [(m*x)+b for x in X]
plt.scatter(X,Y,color='#003F72', label="Input Data")
plt.plot(X, regression_line,color='r', label= "Regression Line")
plt.legend()
#################
Returns:
See figure below.
Linear regression over input data

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store