Back to the blog

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:

Linear regression plot

The linear model \(y = m \cdot x + b\) is fit to the points by minimizing the sum of squared residuals:

\[\min_{m,\,b} \sum_{i=1}^{n} \left(y_i - (m\,x_i + b)\right)^2\]

By differentiating with respect to \(m\) and \(b\) and setting equal to zero, the normal equations are obtained:

\[\frac{\partial S}{\partial m} = -2 \sum_{i=1}^{n} x_i \left(y_i - m\,x_i - b\right) = 0\]
\[\frac{\partial S}{\partial b} = -2 \sum_{i=1}^{n} \left(y_i - m\,x_i - b\right) = 0\]

Solving, the least-squares estimates are:

\[m = \frac{\sum_{i=1}^{n} (x_i - \bar{x})(y_i - \bar{y})}{\sum_{i=1}^{n} (x_i - \bar{x})^2} \qquad b = \bar{y} - m\,\bar{x}\]

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.

Back to the blog