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.

Intermediate 6 min readLesson 6 of 14 Interview Q&A

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

SetUsed forTypical share
TrainingFitting model parameters60–80%
ValidationChoosing hyperparameters, features, models; early stopping10–20%
TestOne final, unbiased estimate — touched once at the end10–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).

Python
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.

LeakExample
Target leakagePredicting hospital readmission using "number of follow-up visits", recorded after the outcome
Preprocessing leakageFitting a scaler, imputer or feature selector on the full dataset before splitting
Temporal leakageRandom splits of time-series data, letting the model see the future
Duplicate / group leakageThe 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 fraudPredicted legitimate
Actually fraudTP = 85 (caught)FN = 15 (missed)
Actually legitimateFP = 30 (false alarm)TN = 870
MetricFormulaQuestion it answersHere
Accuracy(TP+TN) / allHow often is it right overall?95.5%
PrecisionTP / (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%
SpecificityTN / (TN+FP)Of legitimate transactions, how many pass?96.7%
F12·P·R / (P+R)Harmonic mean of precision and recall79.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:

PrioritiseWhen false… are costlyExamples
RecallNegatives (missing a positive)Cancer screening, fraud detection, safety issues
PrecisionPositives (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.
Python
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

MetricFormulaNotes
MAEmean of absolute errorsRobust to outliers; same units as the target
MSE / RMSEmean of squared errors / its rootPunishes big errors; RMSE in target units
MAPEmean of absolute percentage errorsIntuitive; breaks near zero
R²1 − SSE/SSTFraction 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

DiagnosisTraining errorValidation errorFix
High bias (underfitting)HighHigh (close to training)Bigger model, more features, less regularisation, train longer
High variance (overfitting)LowMuch higherMore data, regularisation, dropout, simpler model, augmentation, early stopping
Good fitLowLow, close to trainingShip 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).
Key takeaways
  • 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.
Interview questions
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.