Linear Regression with Python
Example of how to fit a linear regression model with Python using sklearn and plot it with matplotlib.
# libraries used
import numpy as np
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
# Data
x = np.array([20, 40, 60, 80, 100, 120])
y = np.array([220, 200, 180, 170, 150, 135])
# Creating the linear_regression object
linear_regression = LinearRegression()
linear_regression.fit(x.reshape(-1, 1), y)
# The linear model: y = m*x + b
# =========================================
# Intercept with y-axis
b = linear_regression.intercept_
# Slope
m = linear_regression.coef_
# Showing the results
print(f"The intercept is: {b:.3f}")
print(f"The slope is: {m[0]:.3f}")
# Plotting the data x and y, and the linear equation
plt.scatter(x, y, color = "blue")
plt.plot(x, m*x + b, color = "red")
plt.xlabel("x")
plt.ylabel("y")
plt.title("Linear Regression")
plt.grid()
plt.show()
Running it produces the following plot:

The linear model \(y = m \cdot x + b\) is fit to the points by minimizing the sum of squared residuals:
By differentiating with respect to \(m\) and \(b\) and setting equal to zero, the normal equations are obtained:
Solving, the least-squares estimates are:
where \(\bar{x}\) and \(\bar{y}\) are the means of \(x\) and \(y\) respectively.
The animation shows what those two equations do. The second forces the line through \((\bar{x}, \bar{y})\), so the line pivots on that point; each square is a squared residual, and the sum of their areas is smallest exactly at the slope the first one gives.
Animation (needs JavaScript): the line pivots on the centroid and the sum of squared residuals reaches its minimum, 31.9, at m = −0.836 and b = 234.333.