🎓 A1Learner
🔍
0 of 50 lessons completed

Python ML Linear Regression from Scratch

Linear regression from scratch is the same line, built with plain NumPy. The slope formula uses only means and differences.

Slope on tiny data

Three points sit exactly on a line. The formula finds slope 2 and intercept 0.

import numpy as np

x = np.array([1.0, 2.0, 3.0])
y = np.array([2.0, 4.0, 6.0])
slope = np.sum((x - x.mean()) * (y - y.mean())) / np.sum((x - x.mean()) ** 2)
intercept = y.mean() - slope * x.mean()
print(round(float(slope), 4))
print(round(float(intercept), 4))

The mean point sits on the line

Every best-fit line passes through the mean of x and the mean of y.

import numpy as np

x = np.array([1.0, 2.0, 3.0, 4.0])
y = np.array([2.0, 3.0, 5.0, 4.0])
print(round(float(x.mean()), 4))
print(round(float(y.mean()), 4))

Predict with the formula

A prediction is the slope times the input, plus the intercept.

import numpy as np

slope = 2.0
intercept = 1.0
print(slope * 4.0 + intercept)
print(slope * 0.0 + intercept)

Example

import numpy as np
from sklearn.datasets import fetch_california_housing
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split

housing = fetch_california_housing()
X = housing.data[:, [0]]
y = housing.target
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
x = X_train[:, 0]
slope = np.sum((x - x.mean()) * (y_train - y_train.mean())) / np.sum((x - x.mean()) ** 2)
intercept = y_train.mean() - slope * x.mean()
scratch_pred = slope * X_test[:, 0] + intercept
scratch_r2 = 1 - np.sum((y_test - scratch_pred) ** 2) / np.sum((y_test - y_test.mean()) ** 2)
model = LinearRegression()
model.fit(X_train, y_train)
sklearn_pred = model.predict(X_test)
print("From scratch slope:", round(float(slope), 4))
print("From scratch intercept:", round(float(intercept), 4))
print("From scratch test score:", round(float(scratch_r2), 4))
print("sklearn slope:", round(float(model.coef_[0]), 4))
print("sklearn intercept:", round(float(model.intercept_), 4))
print("sklearn test score:", round(model.score(X_test, y_test), 4))
print("Same predictions:", np.allclose(scratch_pred, sklearn_pred))

Key points

  • Slope: the rise of the line for each step along the input
  • Use the mean of x and the mean of y as the centre of the data
  • Subtract each mean from its values to get the differences
  • Multiply the x differences by the y differences, then add them up
  • Divide by the sum of the squared x differences to get the slope
  • Intercept: the mean of y minus the slope times the mean of x
  • Residual: the gap between a real value and the line value

In this example, the same California homes and the same split from the last lesson are used again. The slope formula adds up the products of the x differences and the y differences, then divides by the sum of the squared x differences. The intercept comes from the two means. The from-scratch predictions and the sklearn predictions match exactly. The test score of 0.4708 is the same for both, so the two lines are the same line.

Note

The from-scratch line must match sklearn on the same data. The check at the end of the example proves it.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

How do you find the intercept from the slope?