Module 2 of 6 · 45 minutes

Regression: predicting numbers

From sales forecasts to delivery times, many business questions are 'how much?' This module covers the workhorse model for those questions.

By · Last updated

Learning objectives

  • Explain linear regression
  • Train a regression model and compare with a mean baseline
  • Interpret MAE, RMSE and R²
  • Read coefficients carefully
  • Inspect errors visually
  • Break residuals down by group
  • Compare a linear model with a more flexible one
Setup: the data and models from earlier modules (runs automatically when you press Run on any cell)
Python · setupimport numpy as np
import pandas as pd

rng = np.random.default_rng(42)
n = 2000
customers = pd.DataFrame({
    "tenure_months":   rng.integers(1, 60, n),
    "monthly_spend":   rng.normal(40, 15, n).clip(5, 120).round(2),
    "support_tickets": rng.poisson(1.2, n),
    "on_promo":        rng.integers(0, 2, n),
    "region":          rng.choice(["UK", "IE"], n, p=[0.75, 0.25]),
})
# Hidden "true" pattern: short tenure and many tickets raise churn risk
logit = (1.2 - 0.06 * customers["tenure_months"] + 0.55 * customers["support_tickets"]
         - 0.02 * customers["monthly_spend"] + 0.4 * customers["on_promo"])
customers["churned"] = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
# Annual value we might want to predict (regression)
customers["annual_value"] = (customers["monthly_spend"] * 12 * (1 - 0.3 * customers["churned"])
                             + rng.normal(0, 40, n)).round(2)

from sklearn.model_selection import train_test_split

2.1 Linear regression: drawing the best line

Linear regression predicts a number as a weighted sum of the features plus a constant. Training finds the weights that minimise the squared differences between predictions and actual values. It's fast, interpretable and a strong first model for regression.

With one feature you can picture it as the straight line that passes closest to a cloud of points. With four features it's the same idea in more dimensions: one weight per feature, each saying "for every extra unit of this, move the prediction by that much".

residual = actual − predictedbest-fit lineannual value (£)monthly spend (£) →
Linear regression draws the line that minimises the squared residuals — the vertical gaps between each point and the line.

2.2 Train and evaluate

Python · predicting annual customer valuefrom sklearn.linear_model import LinearRegression
from sklearn.dummy import DummyRegressor
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score

reg_features = ["tenure_months", "monthly_spend", "support_tickets", "on_promo"]
Xr, yr = customers[reg_features], customers["annual_value"]
Xr_train, Xr_test, yr_train, yr_test = train_test_split(Xr, yr, test_size=0.2, random_state=0)

base = DummyRegressor(strategy="mean").fit(Xr_train, yr_train)
lin = LinearRegression().fit(Xr_train, yr_train)

for name, m in [("Baseline (mean)", base), ("Linear regression", lin)]:
    pred = m.predict(Xr_test)
    mae = mean_absolute_error(yr_test, pred)
    rmse = mean_squared_error(yr_test, pred) ** 0.5
    print(f"{name:18}  MAE £{mae:6.1f}   RMSE £{rmse:6.1f}   R² {r2_score(yr_test, pred):.2f}")

2.3 Regression metrics

MetricMeaningUse when
MAE (mean absolute error)Average size of errors, in the target's unitsEasy to explain: "off by £40 on average"
RMSE (root mean squared error)Like MAE but penalises big errors moreLarge errors are especially costly
R²Share of the variation explained, compared with predicting the mean (1 is perfect, 0 is no better than the mean)Comparing models on the same data

Which should you report? Lead with MAE for a business audience, because it is in pounds. Watch RMSE alongside it: when RMSE is much larger than MAE, a few predictions are badly wrong, and those may matter more than the average.

2.4 Reading the coefficients

coefs = pd.Series(lin.coef_, index=reg_features).round(2)
print(coefs)
print("Intercept:", round(lin.intercept_, 2))
# e.g. monthly_spend ≈ +10: each extra £1 of monthly spend adds about £10 of annual value

Coefficients show how the prediction changes when one feature rises by one unit, holding the others constant. They're easy to explain — but they describe association, not causation, and become unreliable when features are strongly correlated with each other.

Take care comparing coefficients with each other: on_promo moves from 0 to 1, while tenure_months ranges from 1 to 59, so "one unit" means very different things. To compare the strength of features, scale them first (Module 4) or use permutation importance (Module 6).

2.5 Check the errors, not just the score

import matplotlib.pyplot as plt

pred = lin.predict(Xr_test)
plt.scatter(yr_test, pred, s=8, alpha=0.5)
plt.plot([yr_test.min(), yr_test.max()], [yr_test.min(), yr_test.max()], "r--")
plt.xlabel("Actual annual value (£)"); plt.ylabel("Predicted (£)")
plt.show()

Points close to the diagonal are good predictions. Patterns — such as consistent under-prediction for high-value customers — suggest missing features or a non-linear relationship.

2.6 Residuals: where is the model wrong?

A residual is the actual value minus the prediction. An average error near zero overall can hide groups where the model is consistently too high or too low. Break the residuals down by something you care about:

Python · average error by ticket countcheck = Xr_test.copy()
check["residual"] = yr_test - lin.predict(Xr_test)
tickets = check["support_tickets"].clip(upper=4)
print(check.groupby(tickets)["residual"].agg(["mean", "count"]).round(1))

A positive mean residual says the model predicts too low for that group; negative says too high. Here the model is about right for customers with no tickets or one, and clearly too high for those with two or three: they are worth less than a straight line expects, because they are the ones who tend to churn. (The 4+ group has only a handful of customers, so its average can't be trusted.) A single overall MAE would never show you that.

2.7 When a straight line isn't enough

In this dataset annual value depends on spend and on whether the customer leaves — and churn itself depends on tenure and tickets in a curved way. Linear regression can only add effects up. Tree-based models (Module 4) can learn "if this and that" patterns. Compare the two:

Python · linear vs a tree-based modelfrom sklearn.ensemble import HistGradientBoostingRegressor

gbr = HistGradientBoostingRegressor(random_state=0).fit(Xr_train, yr_train)
for name, m in [("Linear regression", lin), ("Gradient boosting", gbr)]:
    print(f"{name:18}  MAE £{mean_absolute_error(yr_test, m.predict(Xr_test)):.1f}")

The scores are close: the more flexible model gains little here, and may even do slightly worse. That is a useful result in itself. Much of the remaining error is noise that no model can predict, and when a simple, explainable model performs about as well as a complex one, the simple one is usually the better choice.

Exercise: add a feature

Add region to the regression by one-hot encoding it (e.g. with pd.get_dummies(..., drop_first=True)). Does MAE improve? Why or why not?

Your turn# Write your code here, then press Run
Show a solution
Xr2 = pd.get_dummies(customers[reg_features + ["region"]], columns=["region"], drop_first=True)
Xa, Xb, ya, yb = train_test_split(Xr2, yr, test_size=0.2, random_state=0)
m = LinearRegression().fit(Xa, ya)
print(round(mean_absolute_error(yb, m.predict(Xb)), 1))
# Little or no improvement: region played no part in how this synthetic data was generated.
Exercise: price a new customer

A new customer has been with you 3 months, spends £55 a month, has raised 2 support tickets and is not on a promotion. Build a one-row DataFrame and use lin to predict their annual value. What happens to the prediction if they had raised 5 tickets?

Your turnnew = pd.DataFrame([{"tenure_months": 3, "monthly_spend": 55, "support_tickets": 2, "on_promo": 0}])

# Predict with lin, then press Run
Show a solution
new = pd.DataFrame([{"tenure_months": 3, "monthly_spend": 55, "support_tickets": 2, "on_promo": 0}])
print("Predicted annual value: £", round(lin.predict(new)[0], 2))

new["support_tickets"] = 5
print("With 5 tickets:         £", round(lin.predict(new)[0], 2))

Key takeaways

  • Linear regression fits a weighted sum of features.
  • MAE is the average error in real units; RMSE punishes big errors; R² compares with predicting the mean.
  • Coefficients show association, not causation.
  • Plot predicted vs actual to find systematic errors.
  • Residuals by group reveal where a model is consistently too high or too low.
  • If a simple model performs about as well as a complex one, prefer the simple one.