Model Evaluation
Measuring models honestly — train/validation/test splits, cross-validation, data leakage, the confusion matrix, accuracy, precision, recall, F1, ROC-AUC and PR-AUC, regression metrics, class imbalance, the bias–variance trade-off, learning curves, and hyperparameter tuning.
A model is only as trustworthy as its evaluation. Most ML failures in practice aren't bad algorithms — they're misleading evaluations: leakage, the wrong metric, or testing on data that doesn't resemble production.
Splitting the data
| Set | Used for | Typical share |
|---|---|---|
| Training | Fitting model parameters | 60–80% |
| Validation | Choosing hyperparameters, features, models; early stopping | 10–20% |
| Test | One final, unbiased estimate — touched once at the end | 10–20% |
If you repeatedly tune against the test set, it silently becomes a validation set and your reported score is optimistic.
How to split matters as much as how much:
- Stratify classification splits to keep class proportions.
- Time series: train on the past, validate on the future — never shuffle across time.
- Grouped data: keep all rows of a user/patient/session in the same split, or the model will recognise individuals rather than learn general patterns.
Cross-validation
With limited data, k-fold cross-validation gives a more reliable estimate: split into k folds, train on k−1 and validate on the remaining one, rotate, and average the k scores (with their spread).
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.ensemble import RandomForestClassifier
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
scores = cross_val_score(RandomForestClassifier(), X, y, cv=cv, scoring="f1")
print(f"F1 = {scores.mean():.3f} ± {scores.std():.3f}")Use TimeSeriesSplit for temporal data and GroupKFold for grouped data.
Data leakage
Leakage is information in training that won't be available at prediction time — producing great offline scores and failure in production.
| Leak | Example |
|---|---|
| Target leakage | Predicting hospital readmission using "number of follow-up visits", recorded after the outcome |
| Preprocessing leakage | Fitting a scaler, imputer or feature selector on the full dataset before splitting |
| Temporal leakage | Random splits of time-series data, letting the model see the future |
| Duplicate / group leakage | The same patient or near-duplicate images in train and test |
Fix: split first, then fit all preprocessing inside a pipeline on training folds only. Suspect leakage whenever results look too good to be true.
Classification metrics
The confusion matrix
For 1,000 transactions, 100 of them actually fraudulent:
| Predicted fraud | Predicted legitimate | |
|---|---|---|
| Actually fraud | TP = 85 (caught) | FN = 15 (missed) |
| Actually legitimate | FP = 30 (false alarm) | TN = 870 |
| Metric | Formula | Question it answers | Here |
|---|---|---|---|
| Accuracy | (TP+TN) / all | How often is it right overall? | 95.5% |
| Precision | TP / (TP+FP) | When it flags fraud, how often is it right? | 73.9% |
| Recall (sensitivity, TPR) | TP / (TP+FN) | Of all fraud, how much did it catch? | 85.0% |
| Specificity | TN / (TN+FP) | Of legitimate transactions, how many pass? | 96.7% |
| F1 | 2·P·R / (P+R) | Harmonic mean of precision and recall | 79.1% |
The accuracy trap
With 1% fraud, a model that always predicts "not fraud" scores 99% accuracy and catches nothing. For imbalanced problems, use precision, recall, F1, PR-AUC — never accuracy alone.
Precision vs recall
Moving the decision threshold trades one for the other:
| Prioritise | When false… are costly | Examples |
|---|---|---|
| Recall | Negatives (missing a positive) | Cancer screening, fraud detection, safety issues |
| Precision | Positives (false alarms) | Spam filtering (don't lose real email), recommending content, auto-banning users |
Choose the threshold from business costs, not the default 0.5.
ROC-AUC and PR-AUC
- The ROC curve plots recall (TPR) against the false positive rate across all thresholds. ROC-AUC is the probability that a random positive is scored above a random negative (0.5 = random, 1.0 = perfect). Threshold-independent, but can look flattering on heavily imbalanced data.
- The precision–recall curve and PR-AUC (average precision) focus on the positive class — more informative when positives are rare.
- Log loss and calibration (do predicted 70% probabilities happen 70% of the time?) matter when probabilities drive decisions.
from sklearn.metrics import classification_report, roc_auc_score, average_precision_score
proba = model.predict_proba(X_test)[:, 1]
print(classification_report(y_test, proba > 0.35)) # a tuned threshold
print("ROC-AUC", roc_auc_score(y_test, proba), "PR-AUC", average_precision_score(y_test, proba))Regression metrics
| Metric | Formula | Notes |
|---|---|---|
| MAE | mean of absolute errors | Robust to outliers; same units as the target |
| MSE / RMSE | mean of squared errors / its root | Punishes big errors; RMSE in target units |
| MAPE | mean of absolute percentage errors | Intuitive; breaks near zero |
| R² | 1 − SSE/SST | Fraction of variance explained (1 = perfect, 0 = predicting the mean) |
Handling class imbalance
- Use the right metrics (above) and stratified splits.
- Class weights (
class_weight="balanced") to penalise mistakes on the rare class more. - Resampling: oversample the minority (SMOTE) or undersample the majority — on the training set only.
- Tune the decision threshold.
- Sometimes reframe as anomaly detection.
Bias, variance and learning curves
| Diagnosis | Training error | Validation error | Fix |
|---|---|---|---|
| High bias (underfitting) | High | High (close to training) | Bigger model, more features, less regularisation, train longer |
| High variance (overfitting) | Low | Much higher | More data, regularisation, dropout, simpler model, augmentation, early stopping |
| Good fit | Low | Low, close to training | Ship it (after the test set agrees) |
Learning curves (error vs training-set size) show whether more data would help: if validation error is still falling as data grows, collect more.
Hyperparameter tuning
- Grid search: try every combination — expensive and wasteful.
- Random search: sample combinations — usually better for the same budget, since only a few hyperparameters matter.
- Bayesian optimisation (Optuna, Hyperopt): model which regions look promising and sample there; prune bad trials early.
- Always tune on validation data / cross-validation, never on the test set.
Beyond the offline score
- Baselines: compare against a trivial model (majority class, last value, simple rules). A complex model that barely beats a baseline isn't worth it.
- Slice analysis: check performance per segment (country, device, new vs returning users, demographic groups) — averages hide failures and unfairness.
- Online evaluation: offline metrics are proxies. Confirm with A/B tests on business metrics, and monitor in production for drift (MLOps).
- For LLMs, evaluation needs task-specific test sets, human or model graders, and checks for hallucination and safety (LLMs).
- Split into train, validation and test; stratify, respect time and groups; touch the test set once.
- Use cross-validation for reliable estimates on limited data.
- Prevent leakage: split first and fit preprocessing inside pipelines on training data only.
- Accuracy misleads on imbalanced data; use precision, recall, F1, PR-AUC; set thresholds by business cost.
- Diagnose bias vs variance with training/validation error and learning curves.
- Tune hyperparameters with random or Bayesian search; compare with baselines; check slices; validate online.
QWhen would you optimise for precision and when for recall?easy
Optimise for recall when missing a positive is expensive — screening for disease or detecting fraud, where a false negative causes serious harm and a false alarm only means an extra review. Optimise for precision when false positives are expensive — a spam filter that sends real email to spam, or automatically banning accounts. In practice you choose the decision threshold based on the relative costs, and often report both, or F1 or PR-AUC.
QWhat is data leakage? Give an example.medium
Leakage happens when training data includes information that won't be available when the model makes real predictions, inflating offline metrics. Examples: a feature recorded after the outcome (the claim payout amount when predicting whether a claim is fraudulent), normalising with statistics computed on the full dataset including test data, or randomly splitting time-series data so the model trains on the future. Prevent it by splitting first, building features only from information available at prediction time, and fitting preprocessing within the training folds.