Sub topic 13
Backtesting estimates once labels arrive
Assume you know binary classification metrics, pandas, scikit-learn, train/validation/test splits, and the contents of a production prediction log. This chapter shows how to test performance estimates against the labels that arrive later.
Why backtesting is necessary
A label-free estimate is a forecast about model quality. It is not ground truth. For example, calibrated probabilities can estimate expected accuracy, and feature drift can warn that accuracy may change. These methods depend on assumptions:
- The probabilities remain calibrated.
- The relationship between features and outcomes has not changed.
- The reference data still represents current traffic.
- The error model sees the same patterns in production as it saw during training.
Backtesting measures whether those assumptions work in your domain. You calculate an estimate using only information available at an earlier time. Later, when labels mature, you calculate the actual metric and compare the two.
Do not compare an estimate for today's predictions with labels that are still incomplete. That would mix a forecast with a biased measurement.
Build prediction-time cohorts
A cohort is a group of predictions made during the same time period. For each cohort, store:
- The prediction timestamp.
- The estimate produced at that time.
- The prediction and model version.
- The date when the label became available.
- The eventual label, when known.
The backtest should replay the information boundary. If you are testing an estimate from January 10, the estimate must not use labels or drift statistics from after January 10.
import numpy as np
import pandas as pd
def backtest_accuracy(predictions, maturity_days=30):
predictions = predictions.copy()
predictions["predicted_at"] = pd.to_datetime(predictions["predicted_at"])
predictions["label_available_at"] = pd.to_datetime(
predictions["label_available_at"]
)
predictions["cohort"] = predictions["predicted_at"].dt.to_period("W")
predictions["realized_at"] = (
predictions["label_available_at"] <=
predictions["predicted_at"] + pd.Timedelta(days=maturity_days)
)
rows = []
for cohort, group in predictions.groupby("cohort"):
mature = group[group["realized_at"] & group["label"].notna()]
if mature.empty:
continue
realized_accuracy = (mature["prediction"] == mature["label"]).mean()
estimated_accuracy = group["estimated_accuracy"].mean()
rows.append({
"cohort": str(cohort),
"n": len(group),
"mature_n": len(mature),
"coverage": len(mature) / len(group),
"estimated_accuracy": estimated_accuracy,
"realized_accuracy": realized_accuracy,
"error": estimated_accuracy - realized_accuracy,
})
return pd.DataFrame(rows)
predictions = pd.DataFrame({
"predicted_at": pd.date_range("2026-01-01", periods=6, freq="D"),
"label_available_at": pd.date_range("2026-01-20", periods=6, freq="D"),
"prediction": [1, 0, 1, 1, 0, 0],
"label": [1, 0, 0, 1, 0, 1],
"estimated_accuracy": [0.84, 0.83, 0.82, 0.81, 0.80, 0.79],
})
print(backtest_accuracy(predictions, maturity_days=30))The error column is signed bias. A positive value means the estimator was optimistic. A negative value means it was pessimistic. Track both the average signed error and the average absolute error.
Interpret the results
| Result | Likely meaning | Response |
|---|---|---|
| Small error across cohorts | Estimate is reasonably calibrated | Continue monitoring |
| Estimate consistently too high | Optimistic bias or stale calibration | Recalibrate or add a safety margin |
| Error grows after drift | Estimate does not handle distribution change | Investigate weighting or retraining |
| Coverage changes sharply | Label process or maturity assumption changed | Review label latency and missingness |
A single good cohort does not validate an estimator. Use several historical periods, including known incidents and seasonal changes. Also compare estimates separately by model version, geography, product, or risk tier. An accurate overall estimate can hide severe error in a small but important segment.
Reconcile and alert
Define tolerances before looking at results. For example, alert when absolute error exceeds five percentage points in two consecutive mature cohorts. Require a minimum matured sample size and report coverage beside every metric.
A useful monitoring flow is:
Exercise
An estimator reports 0.90 accuracy for three cohorts. The realized accuracies are 0.88, 0.89, and 0.87. What should you check first?
Show answer
Calculate the signed and absolute errors, check matured-label coverage and sample sizes, and determine whether the consistent optimism exceeds the predefined tolerance.