Model Evaluation and Calibration
Introduction
A single accuracy number hides most of what you need to know about a classifier. It does not say which errors the model makes, whether it would hold up on new data, or whether a predicted 80% means something happens about 80% of the time.
By the end of this article you should be able to choose a metric that fits the cost of each error, avoid common evaluation leaks, read a reliability diagram, and recalibrate a model without changing how it ranks examples.
Start With the Split
Metrics estimate performance only if the evaluation data is truly unseen. Use training data to fit, validation data to make decisions, and a test set once, at the end. Common leaks include:
- Fitting scalers, imputers, or feature selection on all the data before splitting.
- Random splits when examples are grouped, so that the same patient or customer appears on both sides.
- Random splits on time-ordered data, which train on the future to predict the past.
- Picking hyperparameters or thresholds on the test set, which turns it into validation data.
Why Accuracy Can Mislead
Consider a condition with 1% prevalence in 10,000 people, and a model that catches 90% of positives and correctly clears 95% of negatives. These figures are a worked example, not a real system.
| Predicted positive | Predicted negative | |
|---|---|---|
| Actually positive (100) | 90 true positives | 10 false negatives |
| Actually negative (9,900) | 495 false positives | 9,405 true negatives |
Accuracy is 94.95%, which is lower than the 99% achieved by always predicting negative. That trivial model catches no positives, though, while this one has recall of 90%. Its precision is only 90 / 585, or about 15.4%: most of its alarms are false, because negatives vastly outnumber positives.
Choosing a Metric
| Metric | Question it answers | Watch out for |
|---|---|---|
| Precision | When it flags a case, how often is it right? | Depends on prevalence and threshold |
| Recall | What share of real positives does it find? | Can be maximized by flagging everything |
| F1 | Harmonic mean of precision and recall | Ignores true negatives and assumes a particular trade-off |
| ROC-AUC | How often does a random positive outrank a random negative? | Can look strong on rare-event problems while precision is poor |
| PR-AUC | How does precision hold up as recall rises? | Its baseline equals prevalence, so compare only with that in mind |
| Brier score | Mean squared error of the predicted probabilities | Reflects both calibration and discrimination |
No metric is best in general. Begin with the decision the model supports, and with the cost of false positives and false negatives. Then choose the metric and threshold accordingly, and report uncertainty: a difference that fits inside the confidence interval of a small test set may not be real.
Calibration
Ranking and calibration are different properties. A model discriminates well if positives get higher scores than negatives. It is calibrated if, among all the cases where it predicts about 0.8, roughly 80% are actually positive. Calibration matters whenever the number itself is used: to compute expected cost, to set a threshold, or to decide when to defer to a person.
A reliability diagram groups predictions into bins and plots the observed frequency in each against its mean prediction. A calibrated model lies near the diagonal. Expected calibration error (ECE) summarizes the gap as a weighted average over bins:
ECE depends on the binning and can be noisy with few examples, so report it together with the diagram and a proper scoring rule such as Brier score or log loss.
This is synthetic data, generated in your browser with a fixed seed. 4,000 labels are drawn from a known probability, and the simulated model reports logits 2.5 times too large, so it is overconfident. Dividing logits by T = 2.5 undoes this by construction, which real models will not match so neatly. Accuracy at a 0.5 threshold does not change with T, because dividing a logit by a positive number cannot change its sign.
Fixing Miscalibration
Recalibration learns a mapping from raw scores to probabilities, on data the model was not trained on. Never fit it on the test set you use to report results.
- Temperature scaling divides logits by one learned value T. It preserves the ranking within each output and has very little capacity to overfit. Guo et al. (2017) found it effective on the modern neural networks they studied.
- Platt scaling fits a logistic regression on the scores. It is simple, and works well when the distortion is roughly sigmoid-shaped.
- Isotonic regression fits a monotonic step function. It is more flexible, and needs more data to avoid overfitting.
Calibration is also relative to a population. A model calibrated on one group or time period may not be calibrated on another, so recheck it after deployment and across important subgroups.
A Reproducible Workflow
This scikit-learn example has been executed. It uses generated data, so its scores say nothing about real problems, and they are deliberately not quoted here.
from sklearn.calibration import CalibratedClassifierCV, calibration_curve
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import average_precision_score, brier_score_loss, roc_auc_score
from sklearn.model_selection import train_test_split
X, y = make_classification(n_samples=20_000, weights=[0.9], flip_y=0.02, random_state=0)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, stratify=y, random_state=0)
base = RandomForestClassifier(n_estimators=200, random_state=0, n_jobs=2)
# Calibration is fitted on internal cross-validation folds, never on the test set.
model = CalibratedClassifierCV(base, method="isotonic", cv=5).fit(X_train, y_train)
p = model.predict_proba(X_test)[:, 1]
print("ROC-AUC:", round(roc_auc_score(y_test, p), 3))
print("PR-AUC: ", round(average_precision_score(y_test, p), 3))
print("Brier: ", round(brier_score_loss(y_test, p), 3))
# Points for a reliability diagram: observed frequency vs mean prediction per bin.
observed, predicted = calibration_curve(y_test, p, n_bins=10, strategy="quantile")References
- Guo, C., Pleiss, G., Sun, Y., & Weinberger, K. Q. (2017). On Calibration of Modern Neural Networks. ICML.
- Niculescu-Mizil, A., & Caruana, R. (2005). Predicting Good Probabilities with Supervised Learning. ICML.
- Platt, J. (1999). Probabilistic Outputs for Support Vector Machines and Comparisons to Regularized Likelihood Methods. Advances in Large Margin Classifiers.
- Saito, T., & Rehmsmeier, M. (2015). The Precision-Recall Plot Is More Informative than the ROC Plot When Evaluating Binary Classifiers on Imbalanced Datasets. PLOS ONE.
- Brier, G. W. (1950). Verification of Forecasts Expressed in Terms of Probability. Monthly Weather Review, 78(1), 1-3.
- Naeini, M. P., Cooper, G. F., & Hauskrecht, M. (2015). Obtaining Well Calibrated Probabilities Using Bayesian Binning. AAAI.