Predictive Models
Predictive models: training and test sets, MAE and RMSE, overfitting, cross-validation, logistic regression and the confusion matrix, with Julia, R and Python code.
https://morrisonkuhlsen.com/en/data-analysis/predictive-models

Figure 1. Two models fitted to the same 6 training days (blue points) and evaluated on 3 new days (orange diamonds). The degree-5 curve hits the training data exactly and misses the new days by more than the line does. Generated by the Python code in section 4.
A predictive model is a rule, fitted to data already observed, that makes a guess about a value not yet known: how many ice creams a shop will sell tomorrow, given the temperature forecast; whether a car has a manual transmission, given its weight. What matters in a predictive model is making small errors on cases it has not seen yet, and that is what this page teaches you to measure.
The path is: what predicting means (section 1), splitting data into training and test sets (2), measuring the error (3), overfitting (4), cross-validation (5), classification with logistic regression and the confusion matrix (6), other models (7) and cautions (8). The worked examples use small numbers; the examples with real data use the mtcars table that ships with R.
All code comes in three languages, Julia, R and Python: pick yours in the header of any block, and the choice applies to the whole page. The three versions do the same computation and give the same numbers.
1. Predicting and Explaining
The same models (a linear regression, for example) serve two different goals:
- explaining: understanding how the response relates to each variable. The coefficients, the tests and the model assumptions matter;
- predicting: getting the response right in new cases. The size of the error in those cases matters; a model that is hard to interpret is fine if it predicts well.
Prediction problems are split by the type of response:
| Type | The response is | Example | Section |
|---|---|---|---|
| Regression | a number | ice creams sold in a day; a car’s fuel economy | 2 to 5 |
| Classification | a category | manual or automatic transmission; spam or not | 6 |
The variables used to predict are called predictors (or explanatory variables); the one to be predicted is the response.
2. Training and Test Sets
A model always looks good on the data it was fitted to: it was chosen precisely to pass close to them. To find out how it does on new cases, part of the data is set aside and not used for fitting:
- training set: the data used to fit the model;
- test set: the data held back, used only to measure the prediction error.
2.1 Worked example: ice cream sales
Data (illustrative numbers): maximum temperature ($x$, in °C) and ice creams sold ($y$) by a shop on 9 days. Six days form the training set, three are kept for the test.
| Day | Temperature $x$ (°C) | Sales $y$ | |
|---|---|---|---|
| Training | 1 | 20 | 52 |
| 2 | 22 | 57 | |
| 3 | 24 | 71 | |
| 4 | 26 | 81 | |
| 5 | 28 | 87 | |
| 6 | 30 | 102 | |
| Test | 7 | 21 | 58 |
| 8 | 25 | 72 | |
| 9 | 29 | 99 |
Model: the least squares line $\hat{y} = a + b\,x$, fitted only with the 6 training days, with
\[b = \frac{S_{xy}}{S_{xx}} = \frac{\sum (x_i - \bar{x})(y_i - \bar{y})}{\sum (x_i - \bar{x})^2}, \qquad a = \bar{y} - b\,\bar{x}.\]Step 1: training means.
\[\bar{x} = \frac{20 + 22 + 24 + 26 + 28 + 30}{6} = \frac{150}{6} = 25 \qquad \bar{y} = \frac{52 + 57 + 71 + 81 + 87 + 102}{6} = \frac{450}{6} = 75\]Step 2: deviations, products and squares.
| Day | $x - 25$ | $y - 75$ | $(x - 25)(y - 75)$ | $(x - 25)^2$ |
|---|---|---|---|---|
| 1 | −5 | −23 | 115 | 25 |
| 2 | −3 | −18 | 54 | 9 |
| 3 | −1 | −4 | 4 | 1 |
| 4 | 1 | 6 | 6 | 1 |
| 5 | 3 | 12 | 36 | 9 |
| 6 | 5 | 27 | 135 | 25 |
| Sum | 0 | 0 | $S_{xy} = 350$ | $S_{xx} = 70$ |
Step 3: coefficients.
\[b = \frac{350}{70} = 5 \qquad a = 75 - 5 \times 25 = 75 - 125 = -50\]Result: $\hat{y} = -50 + 5\,x$. Each extra degree of maximum temperature is associated, on average, with 5 more ice creams sold (within the observed range, from 20 °C to 30 °C).
Step 4: predictions and errors on the test set. The prediction error is $e = y - \hat{y}$ (actual minus predicted).
| Day | $x$ | Prediction $\hat{y} = -50 + 5x$ | Actual $y$ | Error $e$ |
|---|---|---|---|---|
| 7 | 21 | $-50 + 105 = 55$ | 58 | 3 |
| 8 | 25 | $-50 + 125 = 75$ | 72 | −3 |
| 9 | 29 | $-50 + 145 = 95$ | 99 | 4 |
The line missed by 3, 3 and 4 ice creams on the new days. The next section sums these errors up in a single number.
3. Measuring the Error
3.1 The measures
With $n$ predictions and errors $e_i = y_i - \hat{y}_i$, the most common measures are the same as on the Time Series page:
\[\text{MAE} = \frac{1}{n}\sum_{i=1}^{n} \lvert e_i \rvert \qquad \text{RMSE} = \sqrt{\frac{1}{n}\sum_{i=1}^{n} e_i^2} \qquad \text{MAPE} = \frac{100\%}{n}\sum_{i=1}^{n} \left\lvert \frac{e_i}{y_i} \right\rvert\]- MAE (mean absolute error): the typical size of the error, in the units of the response;
- RMSE (root mean squared error): also in the units of the response, but it squares the errors before averaging, so large errors weigh more. It is always greater than or equal to the MAE;
- MAPE (mean absolute percentage error): the error as a percentage of the actual value; it does not work when an actual value is zero or close to zero.
3.2 In the example
With the test errors 3, −3 and 4:
\[\text{MAE} = \frac{\lvert 3 \rvert + \lvert -3 \rvert + \lvert 4 \rvert}{3} = \frac{10}{3} = 3.33 \text{ ice creams}\] \[\text{RMSE} = \sqrt{\frac{3^2 + (-3)^2 + 4^2}{3}} = \sqrt{\frac{9 + 9 + 16}{3}} = \sqrt{\frac{34}{3}} = \sqrt{11.333} = 3.37 \text{ ice creams}\] \[\text{MAPE} = \frac{100\%}{3}\left(\frac{3}{58} + \frac{3}{72} + \frac{4}{99}\right) = \frac{5.17\% + 4.17\% + 4.04\%}{3} = 4.46\%\]Interpretation: on the days that were not used for fitting, the line misses by 3.33 ice creams on average, about 4.46% of sales.
3.3 Compare with a baseline
An error is only “small” or “large” compared with something. The minimum comparison is with a simple baseline: always predict the training mean (75 ice creams), ignoring the temperature. Among all constant predictions, the mean is the one that minimizes the sum of squared errors on the training data, so it is the natural choice.
| Day | Actual $y$ | Prediction (mean) | Error |
|---|---|---|---|
| 7 | 58 | 75 | −17 |
| 8 | 72 | 75 | −3 |
| 9 | 99 | 75 | 24 |
and a MAPE of 19.24%. The line cuts the typical error from 14.67 to 3.33 ice creams: temperature helps a lot with the prediction. A model that does not beat the baseline is useless for prediction, however sophisticated it is.
3.4 Training error vs test error
On the training data itself, the errors of the line are 2, −3, 1, 1, −3 and 2 (for example, day 1: $52 - (-50 + 5 \times 20) = 52 - 50 = 2$), and
\[\text{RMSE}_{\text{training}} = \sqrt{\frac{4 + 9 + 1 + 1 + 9 + 4}{6}} = \sqrt{\frac{28}{6}} = \sqrt{4.667} = 2.16.\]The training error (2.16) is smaller than the test error (3.37). That is expected: the training error is optimistic, because the model was fitted to those very points. Reporting only the training error overstates the quality of the model.
4. Overfitting
A more flexible model can always pass closer to the training points. With 6 points, a degree-5 polynomial (6 coefficients) goes exactly through all of them: zero training error. But it uses that freedom to follow the noise as well, the ups and downs that do not repeat on new days.
| Training RMSE | Test RMSE | Predictions for days 7, 8 and 9 | |
|---|---|---|---|
| Line (degree 1) | 2.16 | 3.37 | 55, 75, 95 |
| Degree-5 polynomial | 0 | 5.96 | 52.05, 76.80, 92.05 |
(values from the code below). The polynomial hits the training data exactly and misses the new days by more (Figure 1). This is overfitting: a small training error and a large test error, because the model learned patterns that are just chance in the training data (James et al., 2021, p. 32). As the model becomes more flexible, the training error only goes down, but the error on new data goes down up to a point and then rises again.
using Statistics, Plots
# Maximum temperature (°C) and ice creams sold per day (illustrative numbers)
temp_train = [20, 22, 24, 26, 28, 30]; sales_train = [52, 57, 71, 81, 87, 102]
temp_test = [21, 25, 29]; sales_test = [58, 72, 99]
# Least squares line fitted ONLY with the training days
b = sum((temp_train .- mean(temp_train)) .* (sales_train .- mean(sales_train))) /
sum((temp_train .- mean(temp_train)) .^ 2)
a = mean(sales_train) - b * mean(temp_train)
println("Line: sales = ", a, " + ", b, " × temperature")
# Error measures: MAE, RMSE and MAPE
mae(e) = mean(abs.(e))
rmse(e) = sqrt(mean(e .^ 2))
mape(e, y) = 100 * mean(abs.(e ./ y))
error_test = sales_test .- (a .+ b .* temp_test)
error_base = sales_test .- mean(sales_train) # baseline: always predict the training mean
println("Test predictions: ", a .+ b .* temp_test, " errors: ", error_test)
println("Line — MAE = ", round(mae(error_test), digits = 4), " RMSE = ", round(rmse(error_test), digits = 4),
" MAPE = ", round(mape(error_test, sales_test), digits = 2), "%")
println("Mean — MAE = ", round(mae(error_base), digits = 4), " RMSE = ", round(rmse(error_base), digits = 4),
" MAPE = ", round(mape(error_base, sales_test), digits = 2), "%")
println("RMSE of the line on the training data itself: ", round(rmse(sales_train .- (a .+ b .* temp_train)), digits = 4))
# Degree-5 polynomial: goes exactly through the 6 training points
# (x centered at 25 so the numerical computation stays stable)
X(t) = hcat([(t .- 25.0) .^ k for k in 0:5]...)
coef5 = X(temp_train) \ sales_train
println("Degree 5 — training RMSE = ", round(rmse(sales_train .- X(temp_train) * coef5), digits = 4),
" test predictions = ", round.(X(temp_test) * coef5, digits = 4),
" test RMSE = ", round(rmse(sales_test .- X(temp_test) * coef5), digits = 4))
# Plot: training, test, line and degree-5 polynomial
grid = range(19.5, 30.5, length = 200)
p = scatter(temp_train, sales_train, label = "Training", color = :royalblue, markersize = 6,
xlabel = "Maximum temperature (°C)", ylabel = "Ice creams sold",
title = "Line vs degree-5 polynomial", legend = :topleft, size = (760, 460))
scatter!(p, temp_test, sales_test, label = "Test", color = :darkorange, markershape = :diamond, markersize = 7)
plot!(p, grid, a .+ b .* grid, label = "Line (degree 1)", color = :gray30, lw = 2)
plot!(p, grid, X(collect(grid)) * coef5, label = "Degree-5 polynomial", color = :crimson, lw = 2, ls = :dash)
savefig(p, "overfitting_icecream_jl.png")
Line: sales = -50.0 + 5.0 × temperature Test predictions: [55.0, 75.0, 95.0] errors: [3.0, -3.0, 4.0] Line — MAE = 3.3333 RMSE = 3.3665 MAPE = 4.46% Mean — MAE = 14.6667 RMSE = 17.0685 MAPE = 19.24% RMSE of the line on the training data itself: 2.1602 Degree 5 — training RMSE = 0.0 test predictions = [52.0547, 76.8047, 92.0547] test RMSE = 5.9629
# Maximum temperature (°C) and ice creams sold per day (illustrative numbers)
train <- data.frame(temp = c(20, 22, 24, 26, 28, 30), sales = c(52, 57, 71, 81, 87, 102))
test <- data.frame(temp = c(21, 25, 29), sales = c(58, 72, 99))
# Least squares line fitted ONLY with the training days
line_fit <- lm(sales ~ temp, data = train)
cat("Line: sales =", coef(line_fit)[1], "+", coef(line_fit)[2], "× temperature\n")
# Error measures: MAE, RMSE and MAPE
mae <- function(e) mean(abs(e))
rmse <- function(e) sqrt(mean(e^2))
mape <- function(e, y) 100 * mean(abs(e / y))
prediction <- predict(line_fit, test)
error_test <- test$sales - prediction
error_base <- test$sales - mean(train$sales) # baseline: always predict the training mean
cat("Test predictions:", prediction, " errors:", error_test, "\n")
cat("Line — MAE =", round(mae(error_test), 4), " RMSE =", round(rmse(error_test), 4),
" MAPE =", round(mape(error_test, test$sales), 2), "%\n")
cat("Mean — MAE =", round(mae(error_base), 4), " RMSE =", round(rmse(error_base), 4),
" MAPE =", round(mape(error_base, test$sales), 2), "%\n")
cat("RMSE of the line on the training data itself:", round(rmse(residuals(line_fit)), 4), "\n")
# Degree-5 polynomial: goes exactly through the 6 training points
# (x centered at 25 so the numerical computation stays stable)
degree5 <- lm(sales ~ poly(I(temp - 25), 5, raw = TRUE), data = train)
pred5 <- predict(degree5, test)
cat("Degree 5 — training RMSE =", round(rmse(residuals(degree5)), 4),
" test predictions =", round(pred5, 4),
" test RMSE =", round(rmse(test$sales - pred5), 4), "\n")
# Plot: training, test, line and degree-5 polynomial
grid <- data.frame(temp = seq(19.5, 30.5, length.out = 200))
png("overfitting_icecream_r.png", width = 760, height = 460)
plot(train$temp, train$sales, pch = 19, col = "royalblue", cex = 1.4, ylim = c(40, 110),
xlab = "Maximum temperature (°C)", ylab = "Ice creams sold", main = "Line vs degree-5 polynomial")
points(test$temp, test$sales, pch = 18, col = "darkorange", cex = 2)
lines(grid$temp, predict(line_fit, grid), col = "gray30", lwd = 2)
lines(grid$temp, predict(degree5, grid), col = "red3", lwd = 2, lty = 2)
legend("topleft", c("Training", "Test", "Line (degree 1)", "Degree-5 polynomial"),
col = c("royalblue", "darkorange", "gray30", "red3"), pch = c(19, 18, NA, NA), lty = c(NA, NA, 1, 2), lwd = 2)
invisible(dev.off())
Line: sales = -50 + 5 × temperature Test predictions: 55 75 95 errors: 3 -3 4 Line — MAE = 3.3333 RMSE = 3.3665 MAPE = 4.46 % Mean — MAE = 14.6667 RMSE = 17.0685 MAPE = 19.24 % RMSE of the line on the training data itself: 2.1602 Degree 5 — training RMSE = 0 test predictions = 52.0547 76.8047 92.0547 test RMSE = 5.9629
import numpy as np
import matplotlib.pyplot as plt
# Maximum temperature (°C) and ice creams sold per day (illustrative numbers)
temp_train = np.array([20, 22, 24, 26, 28, 30]); sales_train = np.array([52, 57, 71, 81, 87, 102])
temp_test = np.array([21, 25, 29]); sales_test = np.array([58, 72, 99])
# Least squares line fitted ONLY with the training days
b, a = np.polyfit(temp_train, sales_train, 1)
print(f"Line: sales = {a:.4f} + {b:.4f} × temperature")
# Error measures: MAE, RMSE and MAPE
mae = lambda e: np.mean(np.abs(e))
rmse = lambda e: np.sqrt(np.mean(e**2))
mape = lambda e, y: 100 * np.mean(np.abs(e / y))
prediction = a + b * temp_test
error_test = sales_test - prediction
error_base = sales_test - sales_train.mean() # baseline: always predict the training mean
print("Test predictions:", prediction.round(4), " errors:", error_test.round(4))
print(f"Line — MAE = {mae(error_test):.4f} RMSE = {rmse(error_test):.4f} MAPE = {mape(error_test, sales_test):.2f}%")
print(f"Mean — MAE = {mae(error_base):.4f} RMSE = {rmse(error_base):.4f} MAPE = {mape(error_base, sales_test):.2f}%")
print(f"RMSE of the line on the training data itself: {rmse(sales_train - (a + b * temp_train)):.4f}")
# Degree-5 polynomial: goes exactly through the 6 training points
# (x centered at 25 so the numerical computation stays stable)
coef5 = np.polyfit(temp_train - 25, sales_train, 5)
pred5 = np.polyval(coef5, temp_test - 25)
print(f"Degree 5 — training RMSE = {rmse(sales_train - np.polyval(coef5, temp_train - 25)):.4f}"
f" test predictions = {pred5.round(4)} test RMSE = {rmse(sales_test - pred5):.4f}")
# Plot: training, test, line and degree-5 polynomial
grid = np.linspace(19.5, 30.5, 200)
fig, ax = plt.subplots(figsize=(7.6, 4.6))
ax.scatter(temp_train, sales_train, s=55, color="royalblue", label="Training", zorder=3)
ax.scatter(temp_test, sales_test, s=75, marker="D", color="darkorange", label="Test", zorder=3)
ax.plot(grid, a + b * grid, color="0.3", lw=2, label="Line (degree 1)")
ax.plot(grid, np.polyval(coef5, grid - 25), color="crimson", lw=2, ls="--", label="Degree-5 polynomial")
ax.set_xlabel("Maximum temperature (°C)"); ax.set_ylabel("Ice creams sold")
ax.set_title("Line vs degree-5 polynomial"); ax.legend(loc="upper left")
fig.tight_layout(); fig.savefig("overfitting_icecream_en.png", dpi=100)
Line: sales = -50.0000 + 5.0000 × temperature Test predictions: [55. 75. 95.] errors: [ 3. -3. 4.] Line — MAE = 3.3333 RMSE = 3.3665 MAPE = 4.46% Mean — MAE = 14.6667 RMSE = 17.0685 MAPE = 19.24% RMSE of the line on the training data itself: 2.1602 Degree 5 — training RMSE = 0.0000 test predictions = [52.0547 76.8047 92.0547] test RMSE = 5.9629
5. Cross-Validation
5.1 The idea
Splitting into training and test sets only once has two problems: with little data, the result depends a lot on which cases fell in the test set, and the test data are not used for fitting. $k$-fold cross-validation solves both (James et al., 2021, p. 203):
- split the data into $k$ folds of similar size;
- fit the model on $k - 1$ folds and compute the prediction errors on the fold left out;
- repeat, leaving out each fold once;
- combine the errors of the $k$ rounds into a single measure (here, the RMSE of all the errors).
Each case is predicted exactly once, by a model that has not seen it. In practice, $k = 5$ or $k = 10$ is used (James et al., 2021, p. 203). Cross-validation also serves to compare models and choose among them.
The folds are usually drawn at random. In the code below they are fixed, so that the three languages give the same numbers: the car in position $i$ of the table goes to fold $((i - 1) \bmod 5) + 1$, that is, cars 1, 6, 11, … form fold 1, cars 2, 7, 12, … fold 2, and so on.
5.2 Example with real data: fuel economy vs car weight
The mtcars table has data on 32 car models from 1973–74, published by Motor Trend magazine and analyzed by Henderson and Velleman (1981). We use two columns: fuel economy, in miles per gallon (mpg), and weight, in thousands of pounds.
The code fits polynomials of degree 0 to 4 in weight (degree 0 is always predicting the mean; degree 1 is the line) and compares the training error with the 5-fold cross-validation error:
| Degree | Training RMSE (mpg) | Cross-validation RMSE (mpg) |
|---|---|---|
| 0 (mean) | 5.932 | 6.092 |
| 1 (line) | 2.949 | 3.174 |
| 2 | 2.523 | 2.718 |
| 3 | 2.523 | 2.889 |
| 4 | 2.503 | 2.906 |
Interpretation:
- The training error only goes down with the degree (from 5.932 to 2.503): judging by the training data, degree 4 would look best.
- The cross-validation error is smallest at degree 2 (2.718 mpg) and rises again at degrees 3 and 4: the extra curvature of those degrees follows the noise in the data.
- By the cross-validation criterion, the chosen model is degree 2. The difference between degrees 2, 3 and 4 is small with only 32 cars; another split into folds could change their order. The difference from the mean (6.092) and from the line (3.174) is clear.
- The training error of degree 0, 5.932, is the standard deviation of fuel economy computed with divisor $n$, because the prediction is the mean itself.
using RDatasets, Statistics
# mtcars data (Henderson and Velleman, 1981): 32 cars from 1973–74
# MPG = miles per gallon (fuel economy); WT = weight, in thousands of pounds
cars = dataset("datasets", "mtcars")
n = nrow(cars)
# 5 fixed folds: car i goes to fold ((i − 1) mod 5) + 1, in table order
fold = [(i - 1) % 5 + 1 for i in 1:n]
# Polynomial of degree g in weight (degree 0 = always predict the mean)
design(weight, g) = hcat([weight .^ k for k in 0:g]...)
rmse(e) = sqrt(mean(e .^ 2))
println("degree training RMSE cross-validation RMSE")
for g in 0:4
# Training error: fit and evaluate on the same 32 cars
coef_all = design(cars.WT, g) \ cars.MPG
error_train = cars.MPG .- design(cars.WT, g) * coef_all
# Cross-validation: each fold is predicted by a model that has not seen it
errors_cv = Float64[]
for k in 1:5
train, test = cars[fold .!= k, :], cars[fold .== k, :]
coef = design(train.WT, g) \ train.MPG
append!(errors_cv, test.MPG .- design(test.WT, g) * coef)
end
println(g, " ", round(rmse(error_train), digits = 4), " ", round(rmse(errors_cv), digits = 4))
end
degree training RMSE cross-validation RMSE 0 5.932 6.0922 1 2.9492 3.1742 2 2.5233 2.7181 3 2.5228 2.8887 4 2.5029 2.9059
# mtcars data (Henderson and Velleman, 1981): 32 cars from 1973–74
# mpg = miles per gallon (fuel economy); wt = weight, in thousands of pounds
cars <- mtcars
n <- nrow(cars)
# 5 fixed folds: car i goes to fold ((i − 1) mod 5) + 1, in table order
fold <- (seq_len(n) - 1) %% 5 + 1
rmse <- function(e) sqrt(mean(e^2))
# Polynomial of degree g in weight (degree 0 = always predict the mean)
degree_formula <- function(g) if (g == 0) mpg ~ 1 else mpg ~ poly(wt, g, raw = TRUE)
cat("degree training RMSE cross-validation RMSE\n")
for (g in 0:4) {
# Training error: fit and evaluate on the same 32 cars
error_train <- residuals(lm(degree_formula(g), data = cars))
# Cross-validation: each fold is predicted by a model that has not seen it
errors_cv <- c()
for (k in 1:5) {
model <- lm(degree_formula(g), data = cars[fold != k, ])
test <- cars[fold == k, ]
errors_cv <- c(errors_cv, test$mpg - predict(model, test))
}
cat(g, " ", round(rmse(error_train), 4), " ", round(rmse(errors_cv), 4), "\n")
}
degree training RMSE cross-validation RMSE 0 5.932 6.0922 1 2.9492 3.1742 2 2.5233 2.7181 3 2.5228 2.8887 4 2.5029 2.9059
import numpy as np
import statsmodels.api as sm
# mtcars data (Henderson and Velleman, 1981): 32 cars from 1973–74
# (copy of R's data, downloaded from the Rdatasets repository)
# mpg = miles per gallon (fuel economy); wt = weight, in thousands of pounds
cars = sm.datasets.get_rdataset("mtcars").data
weight, mpg = cars["wt"].to_numpy(), cars["mpg"].to_numpy()
n = len(cars)
# 5 fixed folds: car i goes to fold ((i − 1) mod 5) + 1, in table order
fold = np.arange(n) % 5 + 1
rmse = lambda e: np.sqrt(np.mean(e**2))
print("degree training RMSE cross-validation RMSE")
for g in range(5):
# Polynomial of degree g in weight (degree 0 = always predict the mean)
# Training error: fit and evaluate on the same 32 cars
error_train = mpg - np.polyval(np.polyfit(weight, mpg, g), weight)
# Cross-validation: each fold is predicted by a model that has not seen it
errors_cv = []
for k in range(1, 6):
train, test = fold != k, fold == k
coef = np.polyfit(weight[train], mpg[train], g)
errors_cv.extend(mpg[test] - np.polyval(coef, weight[test]))
print(f"{g} {rmse(error_train):.4f} {rmse(np.array(errors_cv)):.4f}")
degree training RMSE cross-validation RMSE 0 5.9320 6.0922 1 2.9492 3.1742 2 2.5233 2.7181 3 2.5228 2.8887 4 2.5029 2.9059
6. Classification
6.1 Logistic regression
When the response is yes/no (1/0), the model should give a probability, a number between 0 and 1. An ordinary line does not work, because it can go above 1 or below 0 for extreme values of the predictor (James et al., 2021, p. 134). Logistic regression uses the logistic function:
\[p(x) = P(Y = 1 \mid x) = \frac{1}{1 + e^{-(\beta_0 + \beta_1 x)}}\]- $p(x)$: probability that the response is 1 when the predictor equals $x$;
- $\beta_0$, $\beta_1$: coefficients, estimated by maximum likelihood (the values that make the observed data most probable), not by least squares;
- $e$: the base of natural logarithms (2.71828…).
For any value of $\beta_0 + \beta_1 x$, the result lies strictly between 0 and 1. And the logarithm of the odds, $\ln\big(p/(1-p)\big)$, is exactly $\beta_0 + \beta_1 x$: the model is a line on the log-odds scale.
Example with real data. In the mtcars table, the am column gives the transmission (1 = manual, 0 = automatic); 13 of the 32 cars are manual. Fitting the logistic regression of transmission on weight with all 32 cars (code below):
The negative sign of $b_1$ says that heavier cars are less likely to be manual.
Probability for a 3,000-pound car:
\[b_0 + b_1 \times 3 = 12.0404 - 4.0240 \times 3 = 12.0404 - 12.0719 = -0.0315\] \[p = \frac{1}{1 + e^{0.0315}} = \frac{1}{1 + 1.0320} = \frac{1}{2.0320} = 0.4921\](with the full coefficients; the four decimals above are rounded). A car of this weight has a 49.21% probability of having a manual transmission: practically a coin toss.
Reading $b_1$: each extra thousand pounds multiplies the odds of a manual transmission by $e^{-4.0240} = 0.0179$, that is, divides the odds by about 56. Note: this applies to the odds $p/(1-p)$, not to the probability $p$, and it describes an association in these 32 cars from 1973–74, not an effect of weight on the choice of transmission.
6.2 Threshold and confusion matrix
To turn the probability into a decision, a threshold is chosen: here, classify as manual when $p \geq 0.5$. The confusion matrix counts the four possible outcomes (James et al., 2021, p. 152):
| Actual: manual (positive) | Actual: automatic (negative) | |
|---|---|---|
| Predicted: manual | TP: true positive | FP: false positive |
| Predicted: automatic | FN: false negative | TN: true negative |
As in regression, the matrix should come from cases the model has not seen. With the 5-fold cross-validation from section 5 (each car classified by a model fitted without it), the result is:
| Actual: manual | Actual: automatic | Total | |
|---|---|---|---|
| Predicted: manual | TP = 11 | FP = 1 | 12 |
| Predicted: automatic | FN = 2 | TN = 18 | 20 |
| Total | 13 | 19 | 32 |
6.3 Performance measures
The names follow James et al. (2021, p. 152), which lists the synonyms used in each field.
Accuracy, the fraction of correct answers:
\[\text{accuracy} = \frac{TP + TN}{n} = \frac{11 + 18}{32} = \frac{29}{32} = 0.90625\](The code shows 0.9062: that is 29/32 = 0.90625 rounded to four decimals, with the final 5 rounded to even.) On its own, accuracy is misleading when one class is much more common. The baseline here is always predicting “automatic”, the most common class: it gets $19/32 = 0.59375$ right. The model (90.6%) beats this baseline comfortably.
Sensitivity (or recall, or true positive rate), the fraction of actual positives the model finds:
\[\text{sensitivity} = \frac{TP}{TP + FN} = \frac{11}{11 + 2} = \frac{11}{13} = 0.8462\]Specificity, the fraction of actual negatives the model recognizes as negative:
\[\text{specificity} = \frac{TN}{TN + FP} = \frac{18}{18 + 1} = \frac{18}{19} = 0.9474\]Precision (or positive predictive value), the fraction of cases flagged as positive that really are positive:
\[\text{precision} = \frac{TP}{TP + FP} = \frac{11}{11 + 1} = \frac{11}{12} = 0.9167\]F1, the harmonic mean of precision and sensitivity, which is only high when both are:
\[F_1 = \frac{2 \times \text{precision} \times \text{sensitivity}}{\text{precision} + \text{sensitivity}} = \frac{2 \times 0.9167 \times 0.8462}{0.9167 + 0.8462} = 0.88\]or, straight from the counts,
\[F_1 = \frac{2\,TP}{2\,TP + FP + FN} = \frac{22}{22 + 1 + 2} = \frac{22}{25} = 0.88\]Interpretation: of the 13 manual cars, the model found 11; of the 12 it flagged as manual, 11 were. The errors were 2 manual cars taken for automatic and 1 automatic taken for manual.
Note the word precision: here it is a technical term (the fraction of hits among those flagged as positive), different from its everyday meaning of “exactness”.
6.4 The threshold is a choice
The 0.5 threshold is not mandatory. Lowering the threshold makes the model flag more cases as positive: sensitivity goes up or stays the same, and specificity goes down or stays the same. Raising the threshold does the opposite. The choice depends on the cost of each type of error: when missing a positive is serious, a lower threshold is used; when a false alarm is costly, a higher one.
using RDatasets, GLM, DataFrames, Statistics
# mtcars: AM = transmission (1 = manual, 0 = automatic); WT = weight, in thousands of pounds
cars = dataset("datasets", "mtcars")
n = nrow(cars)
# Logistic regression with all 32 cars: P(manual) = 1 / (1 + exp(−(b0 + b1·weight)))
model = glm(@formula(AM ~ WT), cars, Binomial(), LogitLink())
b0, b1 = coef(model)
println("b0 = ", round(b0, digits = 4), " b1 = ", round(b1, digits = 4))
println("P(manual | weight = 3) = ", round(1 / (1 + exp(-(b0 + b1 * 3))), digits = 4))
# Confusion matrix with cross-validation (the same 5 fixed folds) and threshold 0.5
fold = [(i - 1) % 5 + 1 for i in 1:n]
predicted = zeros(Int, n)
for k in 1:5
m = glm(@formula(AM ~ WT), cars[fold .!= k, :], Binomial(), LogitLink())
predicted[fold .== k] = Int.(predict(m, cars[fold .== k, :]) .>= 0.5)
end
actual = cars.AM
TP = sum((predicted .== 1) .& (actual .== 1)); FN = sum((predicted .== 0) .& (actual .== 1))
FP = sum((predicted .== 1) .& (actual .== 0)); TN = sum((predicted .== 0) .& (actual .== 0))
println("TP = $TP FN = $FN FP = $FP TN = $TN")
accuracy = (TP + TN) / n
precision = TP / (TP + FP)
sensitivity = TP / (TP + FN)
specificity = TN / (TN + FP)
F1 = 2 * precision * sensitivity / (precision + sensitivity)
println("accuracy = ", round(accuracy, digits = 4), " precision = ", round(precision, digits = 4),
" sensitivity = ", round(sensitivity, digits = 4),
" specificity = ", round(specificity, digits = 4), " F1 = ", round(F1, digits = 4))
println("Accuracy of always predicting 'automatic': ", round(mean(actual .== 0), digits = 4))
b0 = 12.0404 b1 = -4.024 P(manual | weight = 3) = 0.4921 TP = 11 FN = 2 FP = 1 TN = 18 accuracy = 0.9062 precision = 0.9167 sensitivity = 0.8462 specificity = 0.9474 F1 = 0.88 Accuracy of always predicting 'automatic': 0.5938
# mtcars: am = transmission (1 = manual, 0 = automatic); wt = weight, in thousands of pounds
cars <- mtcars
n <- nrow(cars)
# Logistic regression with all 32 cars: P(manual) = 1 / (1 + exp(−(b0 + b1·weight)))
model <- glm(am ~ wt, data = cars, family = binomial)
b <- coef(model)
cat("b0 =", round(b[1], 4), " b1 =", round(b[2], 4), "\n")
cat("P(manual | weight = 3) =", round(plogis(b[1] + b[2] * 3), 4), "\n")
# Confusion matrix with cross-validation (the same 5 fixed folds) and threshold 0.5
fold <- (seq_len(n) - 1) %% 5 + 1
predicted <- integer(n)
for (k in 1:5) {
m <- glm(am ~ wt, data = cars[fold != k, ], family = binomial)
predicted[fold == k] <- as.integer(predict(m, cars[fold == k, ], type = "response") >= 0.5)
}
actual <- cars$am
TP <- sum(predicted == 1 & actual == 1); FN <- sum(predicted == 0 & actual == 1)
FP <- sum(predicted == 1 & actual == 0); TN <- sum(predicted == 0 & actual == 0)
cat("TP =", TP, " FN =", FN, " FP =", FP, " TN =", TN, "\n")
accuracy <- (TP + TN) / n
precision <- TP / (TP + FP)
sensitivity <- TP / (TP + FN)
specificity <- TN / (TN + FP)
F1 <- 2 * precision * sensitivity / (precision + sensitivity)
cat("accuracy =", round(accuracy, 4), " precision =", round(precision, 4),
" sensitivity =", round(sensitivity, 4), " specificity =", round(specificity, 4),
" F1 =", round(F1, 4), "\n")
cat("Accuracy of always predicting 'automatic':", round(mean(actual == 0), 4), "\n")
b0 = 12.0404 b1 = -4.024 P(manual | weight = 3) = 0.4921 TP = 11 FN = 2 FP = 1 TN = 18 accuracy = 0.9062 precision = 0.9167 sensitivity = 0.8462 specificity = 0.9474 F1 = 0.88 Accuracy of always predicting 'automatic': 0.5938
import numpy as np
import statsmodels.api as sm
import statsmodels.formula.api as smf
# mtcars: am = transmission (1 = manual, 0 = automatic); wt = weight, in thousands of pounds
cars = sm.datasets.get_rdataset("mtcars").data.reset_index(drop=True)
n = len(cars)
# Logistic regression with all 32 cars: P(manual) = 1 / (1 + exp(−(b0 + b1·weight)))
model = smf.logit("am ~ wt", data=cars).fit(disp=0)
b0, b1 = model.params
print(f"b0 = {b0:.4f} b1 = {b1:.4f}")
print(f"P(manual | weight = 3) = {1 / (1 + np.exp(-(b0 + b1 * 3))):.4f}")
# Confusion matrix with cross-validation (the same 5 fixed folds) and threshold 0.5
fold = np.arange(n) % 5 + 1
predicted = np.zeros(n, dtype=int)
for k in range(1, 6):
m = smf.logit("am ~ wt", data=cars[fold != k]).fit(disp=0)
predicted[fold == k] = (m.predict(cars[fold == k]) >= 0.5).astype(int)
actual = cars["am"].to_numpy()
TP = np.sum((predicted == 1) & (actual == 1)); FN = np.sum((predicted == 0) & (actual == 1))
FP = np.sum((predicted == 1) & (actual == 0)); TN = np.sum((predicted == 0) & (actual == 0))
print(f"TP = {TP} FN = {FN} FP = {FP} TN = {TN}")
accuracy = (TP + TN) / n
precision = TP / (TP + FP)
sensitivity = TP / (TP + FN)
specificity = TN / (TN + FP)
F1 = 2 * precision * sensitivity / (precision + sensitivity)
print(f"accuracy = {accuracy:.4f} precision = {precision:.4f} sensitivity = {sensitivity:.4f}"
f" specificity = {specificity:.4f} F1 = {F1:.4f}")
print(f"Accuracy of always predicting 'automatic': {np.mean(actual == 0):.4f}")
b0 = 12.0404 b1 = -4.0240 P(manual | weight = 3) = 0.4921 TP = 11 FN = 2 FP = 1 TN = 18 accuracy = 0.9062 precision = 0.9167 sensitivity = 0.8462 specificity = 0.9474 F1 = 0.8800 Accuracy of always predicting 'automatic': 0.5938
When you run the R version, glm may warn that “fitted probabilities numerically 0 or 1 occurred” in one of the folds. It comes from the heaviest cars (over 5,000 pounds), for which the model gives a practically zero probability of a manual transmission. It is not an error, and the coefficients remain valid.
7. Other Models
Linear and logistic regression are the starting point, and they are often enough. There are more flexible models, all evaluated the same way (test set or cross-validation against a baseline):
- Ridge and lasso regression: linear regression with a penalty that shrinks the coefficients toward zero, which reduces overfitting when there are many predictors (James et al., 2021, p. 237). The lasso can set coefficients to zero, keeping only some of the predictors in the model (James et al., 2021, pp. 241–242). The size of the penalty is chosen by cross-validation.
- Decision trees, random forests and boosting: split the data into groups through successive questions (“weight < 3.3?”) and predict with the mean or the most common class of each group; forests and boosting combine many trees (James et al., 2021, ch. 8).
- Neural networks: very flexible models, used mostly with images, sound and text (James et al., 2021, ch. 10).
More flexibility does not guarantee better predictions: with little data, the simple model often wins, as in the ice cream example. Only validation can tell.
8. Cautions
- Data leakage: no information from the test set may enter the fitting, not even indirectly. If you standardize variables, select predictors or handle missing values, do it with means and standard deviations computed on the training set only (inside each round of cross-validation). Otherwise the measured error comes out optimistic.
- Data over time: in time series the folds are not drawn at random; you train on the past and test on the future, as in the validation over time on the Time Series page.
- The world changes: a model holds for cases similar to the training ones. The cars of 1974 do not represent today’s cars; a sales model fitted before a big change (a pandemic, a new competitor) may stop working.
- Extrapolation: the ice cream line was fitted between 20 °C and 30 °C; predicting for 40 °C is a guess.
- Predicting is not explaining: a model that predicts well may use predictors that have no causal link to the response. To decide what to change in the world, a different kind of analysis is needed.
- Decisions about people: when the model decides something about people (credit, jobs, health), check the errors separately in each relevant group: a model with good overall accuracy can make many more errors in one group than in another.
- Report the baseline, the validation method and the error on new data, not only the training error.
9. Summary
- A predictive model is evaluated by its error on cases it has not seen: split into training and test sets, or use cross-validation.
- Error measures for numerical responses: MAE, RMSE (large errors weigh more; it is always ≥ MAE) and MAPE. In the ice cream example, the line missed by 3.33 ice creams on average on the test set, versus 14.67 for the baseline (predicting the mean).
- The training error is optimistic (2.16 versus 3.37 on the test set). Models that are too flexible suffer from overfitting: the degree-5 polynomial brought the training error to zero and missed more on the test set (5.96).
- $k$-fold cross-validation: each case is predicted by a model that has not seen it. On mtcars, it chose degree 2 (RMSE of 2.718 mpg), while the training error would prefer degree 4.
- Classification: logistic regression gives probabilities between 0 and 1; a threshold turns them into decisions. With cross-validation, the cars’ transmission was predicted with accuracy 0.90625 (baseline 0.59375), sensitivity 0.8462, specificity 0.9474, precision 0.9167 and F1 0.88.
- The threshold, the baseline and the validation method are choices: state which ones were made.
References
- Henderson, H. V.; Velleman, P. F. (1981). Building multiple regression models interactively. Biometrics, 37(2), 391–411. DOI: 10.2307/2530428.
- James, G.; Witten, D.; Hastie, T.; Tibshirani, R. (2021). An Introduction to Statistical Learning: with Applications in R. 2nd ed. Springer. DOI: 10.1007/978-1-0716-1418-1.
Data
- Cars: the
mtcarsdata set from R’sdatasetspackage (R Core Team), extracted from Motor Trend magazine (US, 1974), which cites Henderson and Velleman (1981). In Julia, read with the RDatasets package; in Python, withstatsmodels.datasets.get_rdataset("mtcars"), which downloads the same table from the Rdatasets repository. - Ice cream (sections 2 to 4): illustrative numbers, made up so the arithmetic stays simple.