Evaluating models: metrics, validation and the bias–variance trade-off
How good is it, compared to what, and how sure are you?
Choosing the metric, the validation protocol and the error bars is where most real projects are won or lost — a model that looks 97% accurate can be useless, and a 0.5% improvement can be noise. This lesson gives you the vocabulary of the confusion matrix, the ROC and precision–recall curves, the discipline of cross-validation without leakage, and the bias–variance decomposition that explains why models fail. The same ideas evaluate LLMs (8.7 Evaluating LLMs), RAG systems (9.8 Evaluating and observing LLM apps) and agents (10.9 Evaluating agents).
You'll be able to
- Compute accuracy, precision, recall, F1, specificity and balanced accuracy from a confusion matrix and explain the accuracy paradox
- Read and choose between ROC and precision–recall curves, and interpret AUC as a ranking probability
- Select a validation protocol (holdout, k-fold, stratified, grouped, time-series, nested) and name the leakage each prevents
- Derive the bias–variance decomposition of expected squared error and use it to diagnose underfitting and overfitting
- Read learning curves and decide whether more data, more capacity or more regularization is the fix
- Attach a standard error to an accuracy and decide whether two models actually differ
Key ideas
- A metric is a decision tool: choose one whose change would change what you do, and state what it misses.
- From the confusion matrix: precision = TP/(TP+FP), recall = TP/(TP+FN), F1 = harmonic mean; accuracy misleads under imbalance (the accuracy paradox).
- ROC/AUC measures ranking quality (P(score⁺ > score⁻)) independent of threshold; prefer precision–recall curves when positives are rare.
Show 5 more key ideas
- Set thresholds by expected cost, not 0.5; evaluate probabilities themselves with log loss/Brier and calibration plots.
- k-fold CV gives a mean and a spread; stratify for imbalance, group by entity, split by time for temporal data, nest for honest hyperparameter search; the test set is used once.
- Expected squared error = Bias² + Variance + irreducible noise; capacity lowers bias and raises variance, giving the U-shaped test error.
- Learning curves tell you whether the fix is capacity (both errors high) or data/regularization (persistent gap).
- Accuracy has standard error √(p(1−p)/n); compare models with paired bootstrap or repeated CV, and treat differences within the spread as noise.
Suggested path through this lesson
Evaluation is the hard part
A model is only as good as the number you trust about it, and that number answers three questions: how good (which metric), compared to what (which baseline and which data), and how sure (which error bars). The metric you can compute is rarely the objective you care about — click-through is not satisfaction, token-level loss is not helpfulness — so the first job is to pick a metric whose improvement would actually change a decision, and to say out loud what it misses (3.1 What is learning? ERM, generalization and the ML workflow).
The confusion matrix and what grows from it
For a binary classifier, every prediction lands in one of four cells: true positives (TP), false positives (FP, type I errors), false negatives (FN, type II errors), true negatives (TN). Everything else is a ratio of these.
| metric | formula | reads as |
|---|---|---|
| accuracy | fraction right — misleading when classes are imbalanced | |
| precision | of the things I flagged, how many were real | |
| recall (sensitivity, TPR) | of the real things, how many I caught | |
| specificity (TNR) | of the negatives, how many I left alone | |
| false positive rate | the x-axis of the ROC curve | |
| harmonic mean — punishes whichever is worse | ||
| balanced accuracy | accuracy as if classes were equal |
Worked example. A fraud model on 1,000 transactions: , , , . Accuracy . Precision . Recall . . Specificity , FPR . Balanced accuracy . Now the accuracy paradox: a model that flags nothing scores accuracy and zero recall. Accuracy flattered the fraud model; recall and precision tell you it misses a third of the fraud and that one in five alerts is false. With more than two classes, compute per-class precision/recall and average them: macro (unweighted mean, every class counts equally), weighted (by class frequency), or micro (pool all cells, which for single-label problems equals accuracy).
Thresholds and curves
A probabilistic classifier (3.3 Logistic regression and softmax classification) plus a threshold is a hard classifier; move the threshold and every cell of the matrix changes. The ROC curve plots TPR against FPR as the threshold sweeps from 1 to 0; a random classifier is the diagonal, a perfect one hugs the top-left corner. Its area, AUC, has a clean meaning: the probability that a randomly chosen positive is scored higher than a randomly chosen negative — a measure of ranking quality independent of any threshold. The precision–recall curve plots precision against recall over the same sweep; its area (average precision) is the metric to prefer under heavy imbalance, because precision depends on the base rate while FPR does not: with 1% positives, a model with FPR looks superb on ROC but produces as many false alarms as true detections. The interactive demo makes this concrete — drag the threshold between two overlapping score distributions and watch the matrix, precision, recall, and the ROC point move together.
Which threshold? The one that minimizes expected cost, , where the costs come from the problem (a missed cancer versus an unnecessary biopsy), never from the default 0.5. If what you need is the probability itself — for ranking, for downstream decisions — evaluate it directly with log loss or the Brier score , and check calibration with a reliability diagram (3.3 Logistic regression and softmax classification).
Regression metrics
| metric | formula | notes |
|---|---|---|
| MSE / RMSE | and its root | RMSE is in the units of ; squared error punishes large misses |
| MAE | robust to outliers; the median-like counterpart of MSE | |
| MAPE | explodes near ; asymmetric | |
| fraction of variance explained; can be negative on test data |
Report RMSE and MAE in the target's units with a baseline (predicting the mean gives , RMSE ); a 2.1 RMSE means nothing without knowing that the mean-predictor gets 2.3.
Validation protocols and the leaks they prevent
A single holdout split (e.g., 80/20) is fine with abundant data but gives one noisy number. k-fold cross-validation splits the training data into folds (5 or 10), trains times holding out each fold, and reports the mean and standard deviation across folds — an estimate with a spread. Stratified folds preserve class proportions, essential for imbalance. Grouped folds keep all rows of one entity (patient, user, document) in the same fold, so the model cannot memorize the entity. Time-series splits train on the past and validate on the future (forward chaining), because shuffling time leaks the future into training. Nested cross-validation runs hyperparameter search inside each outer fold, so the outer score is not inflated by the search; use it when you report a number that others will rely on. Through all of this the test set remains untouched until the end (3.1 What is learning? ERM, generalization and the ML workflow).
Leakage is any route by which information about the validation or test targets reaches the training process: scaling, imputing or selecting features on the full dataset before splitting (2.3 pandas, data wrangling and plotting); near-duplicate rows across splits (common in text and images); features recorded after the outcome (an "account closed" flag predicting churn); and temporal leakage. Pipelines that fit every preprocessing step inside each fold (sklearn.pipeline.Pipeline inside cross_val_score) are the mechanical defence (3.14 Project: end-to-end tabular ML with scikit-learn).
The bias–variance decomposition
Why do models fail? Suppose with , , and let be the model trained on a random training set . Fix a test point and write for the average prediction over training sets. The expected squared error at is
The middle term vanishes because is independent of and has mean zero; the last is . Split the first by adding and subtracting :
Therefore
Bias is the systematic error of the average model — a line fit to a curve is biased everywhere. Variance is how much the fitted model wobbles from one training set to the next — a degree-15 polynomial or a 1-NN classifier changes completely when a few points change. Capacity moves you along the curve: more flexible models lower bias and raise variance, and the test error is U-shaped in between (3.1 What is learning? ERM, generalization and the ML workflow). in kNN (3.4 k-Nearest Neighbors), polynomial degree (3.2 Linear regression), tree depth (3.8 Decision trees) and the regularization strength (3.6 Regularization and generalization) are all bias–variance dials. Averaging many high-variance models cancels variance — that is why random forests work (3.9 Ensembles: bagging, random forests and gradient boosting).
Math check. For kNN regression with noise , the variance term is exactly : averaging noisy neighbours divides the noise variance by , while the bias grows as the neighbourhood widens. The trade-off is literal.
Learning curves
Plot training and validation error against the training-set size (or against epochs for iterative models).
| what you see | diagnosis | remedy |
|---|---|---|
| both errors high and close | high bias (underfitting) | more capacity, better features, less regularization, train longer |
| training low, validation high, gap persists as grows | high variance (overfitting) | more data, regularization, simpler model, augmentation, early stopping |
| validation still falling steeply with | data-limited | collecting data will pay off |
| validation flat and near training | capacity-limited | change the model or the features, not the data size |
Are the differences real?
A test accuracy is a sample proportion: with test examples and true accuracy its standard error is (1.8 Statistics essentials). At and that is — a 95% interval of roughly percentage points — so two models at 90.2% and 90.7% are indistinguishable. Because both models are scored on the same examples, compare them paired: bootstrap the per-example differences (resample test items, recompute the difference 1,000 times, read off the interval), or use McNemar's test on the disagreement counts. For cross-validation, report mean standard deviation over folds and, when the decision matters, repeat with several shuffles. A difference smaller than the spread is not a result; this rule survives unchanged into LLM benchmarks, where leaderboards often rank models by gaps smaller than their standard errors (8.7 Evaluating LLMs).
Where this shows up later
- Regularization is the lever that trades bias for variance — 3.6 Regularization and generalization; bagging averages away variance — 3.9 Ensembles: bagging, random forests and gradient boosting.
- Pipelines inside cross-validation are the project discipline of 3.14 Project: end-to-end tabular ML with scikit-learn; grouped and temporal splits reappear in 3.13 Feature engineering, data quality and data-centric ML.
- Precision/recall become recall@k, MRR and nDCG for retrieval — 9.5 Retrieval quality: hybrid search, reranking, query transforms and metrics; faithfulness and answer relevance for RAG — 9.8 Evaluating and observing LLM apps.
- Standard errors, paired comparisons and contamination are the core of LLM evaluation — 8.7 Evaluating LLMs — and agent evaluation (pass@k vs pass^k) — 10.9 Evaluating agents.
Common pitfalls (5)
- Reporting accuracy on imbalanced data; the all-negative baseline may already score 94%.
- Using ROC-AUC alone with 1% positives, where an FPR of 0.01 means as many false alarms as true hits.
- Fitting scalers, imputers or feature selection on the whole dataset before cross-validation (leakage through preprocessing).
- Shuffling time-series data into random folds, so the model trains on the future.
- Declaring a winner from a 0.5-point gap on a 1,000-example test set without computing the standard error.
Recap: all 8 key points
- A metric is a decision tool: choose one whose change would change what you do, and state what it misses.
- From the confusion matrix: precision = TP/(TP+FP), recall = TP/(TP+FN), F1 = harmonic mean; accuracy misleads under imbalance (the accuracy paradox).
- ROC/AUC measures ranking quality (P(score⁺ > score⁻)) independent of threshold; prefer precision–recall curves when positives are rare.
- Set thresholds by expected cost, not 0.5; evaluate probabilities themselves with log loss/Brier and calibration plots.
- k-fold CV gives a mean and a spread; stratify for imbalance, group by entity, split by time for temporal data, nest for honest hyperparameter search; the test set is used once.
- Expected squared error = Bias² + Variance + irreducible noise; capacity lowers bias and raises variance, giving the U-shaped test error.
- Learning curves tell you whether the fix is capacity (both errors high) or data/regularization (persistent gap).
- Accuracy has standard error √(p(1−p)/n); compare models with paired bootstrap or repeated CV, and treat differences within the spread as noise.
Watch
The four cells and the metrics built from them.
Read
Try it live
Interactive demo
runs in your browserExercises
- Metrics by hand, then by code
From , , , compute all seven metrics in the table by hand, then with
sklearn.metricson a synthetic label/prediction pair that reproduces these counts. Expected: accuracy 0.97, precision 0.80, recall 0.667, 0.727, balanced accuracy 0.828. - ROC vs PR under imbalance
Train logistic regression on a dataset with 1% positives (downsample a balanced one). Plot the ROC and PR curves. Expected: ROC-AUC looks high (>0.9) while average precision is modest; explain in two sentences why.
- Leakage, demonstrated
Standardize features and select the top-10 by correlation with the target on the full dataset, then cross-validate; repeat with both steps inside a
Pipeline. Use a dataset with 200 rows and 2,000 pure-noise features. Expected: the leaky version reports impressive accuracy on noise; the pipeline version is at chance. - Bias and variance, simulated
Sample 100 training sets of 30 points from ; fit polynomials of degree 1, 3 and 12 to each; at 50 test x-values compute the average prediction, the squared bias and the variance across training sets. Expected: bias falls and variance rises with degree, and bias² + variance + matches the measured test MSE.
- Is it significant?
Evaluate two classifiers on the same 1,000-example test set, compute the standard error of each accuracy, and bootstrap the paired difference 1,000 times. Expected: a 95% interval for the difference; state whether it excludes zero.
Quiz
Flashcards
These cards are now in your spaced-repetition queue. Review all due cards →