Part IV — Expert Production Engineering · Chapter 19 · Lesson 3 of 7 · 6 min read
Lesson 3: Regression and Classification Metrics
Lesson level: Advanced
Purpose: Measure model quality with metrics that reflect how errors affect the business, compare models against meaningful baselines, and report results honestly.
Learning objectives
By the end of this lesson you will be able to:
- compute and interpret MAE, RMSE, and R² for regression
- build and read a confusion matrix
- compute accuracy, precision, recall, specificity, and F1
- explain ROC AUC and precision-recall AUC and when each is informative
- evaluate predicted probabilities with log loss and the Brier score
- compare models against trivial baselines and report uncertainty
3.1 Regression metrics
Chapter 18 introduced MAE, RMSE, and scaled errors for forecasts. They apply equally to regression models. One additional metric is common:
R² (coefficient of determination) is 1 − (sum of squared errors of the model) / (sum of squared errors of predicting the mean). An R² of 0.6 means the model removes 60% of the squared error that a constant mean prediction would leave. R² can be negative on test data when the model is worse than predicting the training mean. It says nothing about whether errors are small enough for the business; always report it alongside MAE or RMSE in real units.
3.2 The confusion matrix
For a binary classifier with a chosen threshold, every prediction falls into one of four cells:
| Predicted positive | Predicted negative | |
|---|---|---|
| Actual positive | True positive (TP) | False negative (FN) |
| Actual negative | False positive (FP) | True negative (TN) |
Every classification metric is built from these four counts. Before choosing a metric, ask what a false positive and a false negative each cost. Flagging a loyal customer as a churn risk may cost a small discount; missing a real churner may cost a year of revenue. Missing a fraudulent payment may cost the full amount; blocking a legitimate one costs a frustrated customer and a support call.
3.3 Threshold metrics
| Metric | Formula | Question it answers |
|---|---|---|
| Accuracy | (TP + TN) / all | What share of predictions are correct? |
| Precision | TP / (TP + FP) | When the model says positive, how often is it right? |
| Recall (sensitivity) | TP / (TP + FN) | What share of actual positives does the model find? |
| Specificity | TN / (TN + FP) | What share of actual negatives does the model correctly clear? |
| F1 | 2 × precision × recall / (precision + recall) | Balance of precision and recall in one number |
Precision and recall trade off against each other as the threshold moves: lowering the threshold flags more cases, raising recall and usually lowering precision. F1 is a convenient single number when both matter roughly equally, but it ignores true negatives and hides the trade-off. When costs are known, prefer reporting precision and recall at the chosen threshold, plus the expected cost (Lesson 5).
Illustrative listing.
from pealang.ml.metrics import confusion_matrix, precision, recall, f1
cm = confusion_matrix(y_test, label)
print(cm) # {"tp": .., "fp": .., "fn": .., "tn": ..}
print("precision", round(precision(y_test, label), 3))
print("recall", round(recall(y_test, label), 3))
print("f1", round(f1(y_test, label), 3))
3.4 Worked example: why accuracy misleads
A test set holds 1,000 customers, of whom 80 churned. At a chosen threshold the model produces TP = 56, FN = 24, FP = 64, and TN = 856.
- Accuracy = (56 + 856) / 1,000 = 0.912.
- Precision = 56 / 120 ≈ 0.467: fewer than half of flagged customers actually churn.
- Recall = 56 / 80 = 0.70: the model finds 70% of churners.
- Specificity = 856 / 920 ≈ 0.930.
- F1 = 0.56.
A trivial model that predicts "no churn" for everyone scores accuracy 0.92 — higher than the real model — while finding no churners at all. Accuracy rewards the majority class. For rare-event problems, report precision, recall, and the metrics in the next section, and always show the trivial baseline beside the model.
3.5 Ranking metrics: ROC AUC and PR AUC
Threshold metrics depend on one cut-off. Ranking metrics evaluate the probabilities across all thresholds.
- The ROC curve plots recall (true positive rate) against the false positive rate as the threshold moves. ROC AUC is the area under it: the probability that a randomly chosen positive gets a higher score than a randomly chosen negative. 0.5 is random ranking; 1.0 is perfect.
- The precision-recall curve plots precision against recall. PR AUC (often computed as average precision) focuses on the positive class. Its random baseline equals the positive rate — 0.08 in the example above — not 0.5.
With strong imbalance, ROC AUC can look excellent because the huge number of true negatives keeps the false positive rate small. PR AUC shows how hard the problem really is. Report both for imbalanced problems, and always state the positive rate so readers can interpret PR AUC.
3.6 Probability metrics
When predicted probabilities are used directly — for expected-value calculations, pricing, or prioritization — their accuracy matters, not just their ranking.
- Log loss is the average of −log(probability assigned to the actual class). It punishes confident errors severely: predicting 0.99 for an event that does not happen costs far more than predicting 0.6.
- Brier score is the mean squared difference between predicted probability and the 0/1 outcome. It is bounded between 0 and 1 and easier to explain.
Both should be compared with the score of a model that always predicts the base rate. Lesson 5 adds calibration plots, which show where probabilities are too high or too low.
3.7 Reporting results honestly
- Report every metric on the untouched test set once, after choices are frozen.
- Show a trivial baseline (mean for regression, majority class or base rate for classification) beside every model.
- Give uncertainty: a bootstrap interval or the spread across cross-validation folds. A difference of 0.005 in AUC on 300 test rows is noise.
- Report metrics for important segments — regions, products, customer groups — not only overall. A good average can hide a segment where the model fails; Chapter 20 turns this into fairness diagnostics.
- State the threshold used for every threshold metric.
Common mistakes
- Headline accuracy on imbalanced data: compare with the majority-class baseline and report precision and recall.
- F1 as the only metric: it hides the precision-recall trade-off and ignores true negatives.
- Reading PR AUC against 0.5: its baseline is the positive rate.
- Reporting R² alone: include errors in real units.
- No uncertainty: small test sets give noisy metrics.
- No segment analysis: averages hide failures in subgroups.
Guided practice
- From the confusion matrix in Section 3.4, compute the metrics for a threshold that produces TP = 70, FN = 10, FP = 180, TN = 740, and describe the trade-off.
- Compute ROC AUC and PR AUC for a model and for random scores on the same data.
- Bootstrap the test set 500 times and report a 90% interval for recall.
Hands-on lab: A metrics report
- Using the logistic model from Lesson 2, compute the confusion matrix at 0.5, plus accuracy, precision, recall, specificity, and F1.
- Compute ROC AUC, PR AUC, log loss, and Brier score, each beside its trivial baseline.
- Bootstrap 90% intervals for recall, precision, and PR AUC.
- Break precision and recall down by two segments such as region and plan.
- Write a one-page report that a business owner could use to decide whether the model is ready for a pilot.
Review questions
- What does an R² of zero mean?
- Define precision and recall in terms of the confusion matrix.
- Why can accuracy be high for a useless model?
- What does ROC AUC measure, and what is its random baseline?
- Why is PR AUC more informative than ROC AUC for rare events?
- How do log loss and the Brier score differ?
- Why must metrics be reported with uncertainty and by segment?
Applied challenge
A hospital operations team wants to predict missed appointments (about 12% of bookings) to schedule reminder calls. Each call costs a small amount; each missed appointment wastes a clinician slot. Choose the primary and secondary metrics, define the baseline, design the segment analysis (clinic, age band, booking lead time), and write the evaluation section of a model proposal.
Lesson summary
Metrics are statements about which errors matter. Use errors in real units and R² for regression; the confusion matrix, precision, and recall at a stated threshold for decisions; ROC AUC and PR AUC for ranking; and log loss or the Brier score for probabilities. Compare every model with a trivial baseline, report uncertainty and segment results, and never let accuracy alone describe an imbalanced problem.
Transition to Lesson 4
One train/test split gives one noisy estimate and invites over-tuning. Lesson 4 uses cross-validation to compare models reliably, regularization to control complexity, and structured search to choose settings.
Lesson status: Ready for review.