Sub topic 4
Evaluating matured cohorts by prediction time
This chapter assumes you know binary classification metrics (accuracy, precision, recall, ROC AUC), basic pandas and scikit-learn, and what a prediction log is. It also assumes you have read the previous chapters on label delay and on choosing a label maturity window.
The problem with "all predictions with a label"
The obvious production metric is to join the prediction log to whatever labels exist and score the result. This is misleading when labels are delayed. Labels arrive at different speeds for different outcomes. Fast outcomes, such as an immediate chargeback, show up early. Slow outcomes, such as a default after 90 days, show up late. Today's metric over "everything with a label" therefore mixes old predictions that are almost fully labeled with recent predictions that are barely labeled. The labeled part of the recent predictions is a biased sample of the fast-resolving cases.
The fix is to evaluate by cohort. A cohort is the set of predictions made in one time bucket, such as one day or one week, grouped by predicted_at. You score a cohort only when its labels have matured, meaning the maturity window has passed since the cohort's predictions were made.
The working model
Three ideas make up the method.
- Group by prediction time, not label time. A prediction belongs to the cohort of the day it was made. If you group by the date the label arrived, a single day mixes predictions from many different days and the metric no longer describes any model state.
- Score only matured predictions. A prediction is mature when
predicted_at <= now - maturity. After that point you treat a missing label as final. For a prediction that is not yet mature, a missing label means "not known yet." - Report coverage next to the metric. Coverage is the fraction of predictions that qualify as mature. It tells the reader how stale the number is. A metric computed on 40% of last month's traffic means something different from one computed on 95%.
A matured-AUC function
The function below scores only predictions older than the maturity window. It returns the AUC and the coverage.
import pandas as pd
from sklearn.metrics import roc_auc_score
def matured_auc(preds: pd.DataFrame, labels: pd.DataFrame,
now: pd.Timestamp, maturity: pd.Timedelta):
"""AUC on predictions old enough that their label should have arrived.
preds: columns id, predicted_at, score
labels: columns id, label (only rows whose outcome is known)
"""
cutoff = now - maturity
mature = preds[preds["predicted_at"] <= cutoff]
joined = mature.merge(labels[["id", "label"]], on="id", how="left")
# Assumption: after the maturity window, a missing label means "negative"
# (for example, no chargeback was filed). Check this for your domain.
joined["label"] = joined["label"].fillna(0).astype(int)
coverage = len(mature) / len(preds) if len(preds) else 0.0
return roc_auc_score(joined["label"], joined["score"]), coverageSome points about this function:
- The left join keeps every mature prediction. An inner join would drop unlabeled rows, which removes most of the negatives in a fraud setting and inflates every metric that depends on the class balance.
fillna(0)encodes the assumption that silence means negative. This holds for chargebacks and defaults. It does not hold when a missing label means the outcome was never observed, for example a loan that was declined and so never had a chance to default. That case is covered in the next chapter on censoring and selection bias.roc_auc_scoreraises an error if the mature set contains only one class. Guard against this for small or very recent cohorts.
Scoring by cohort
A single number hides trends. To see how the model behaves over time, compute the metric for each cohort. The sketch below builds on matured_auc and uses weekly buckets.
import numpy as np
import pandas as pd
from sklearn.metrics import roc_auc_score
def cohort_report(preds, labels, now, maturity, freq="W"):
"""Per-cohort AUC for cohorts whose every prediction is mature."""
preds = preds.copy()
preds["cohort"] = preds["predicted_at"].dt.to_period(freq)
rows = []
for cohort, group in preds.groupby("cohort"):
# A cohort is mature only when its newest prediction is mature.
newest = group["predicted_at"].max()
if newest > now - maturity:
rows.append({"cohort": str(cohort), "n": len(group),
"auc": np.nan, "status": "immature"})
continue
joined = group.merge(labels[["id", "label"]], on="id", how="left")
joined["label"] = joined["label"].fillna(0).astype(int)
if joined["label"].nunique() < 2:
rows.append({"cohort": str(cohort), "n": len(group),
"auc": np.nan, "status": "one class"})
continue
auc = roc_auc_score(joined["label"], joined["score"])
rows.append({"cohort": str(cohort), "n": len(group),
"auc": auc, "status": "scored"})
return pd.DataFrame(rows)The cohort is scored only when its newest prediction has matured. This is stricter than scoring the mature rows of a partly mature cohort, and it keeps every row in the cohort on the same footing. The trade-off is that your freshest scored cohort lags now by the maturity window plus the width of the bucket.
Choosing bucket width
| Bucket | Strength | Weakness |
|---|---|---|
| Daily | Fast detection of a sudden break | Few positives per bucket, noisy AUC |
| Weekly | Smooths day-of-week effects | Adds up to six days of extra lag |
| Monthly | Stable estimates for rare outcomes | Slow, and hides short incidents |
Pick the bucket so that each cohort holds enough positives for a stable metric. As a rough rule, aim for at least a few hundred positives per cohort for AUC. If outcomes are rare, widen the bucket rather than trusting a noisy estimate.
Edge cases
- Mixed delays. If a product has several outcome types with different delays, one maturity window is a compromise. A short window includes cohorts where slow outcomes are still missing, which biases the label rate down. A long window delays everything. Consider scoring each outcome with its own window.
- Late-arriving corrections. Labels can change after the window, such as a disputed chargeback that is reversed. Keep the label table versioned, or re-score old cohorts on a schedule, so a past metric can be reproduced.
- Model version changes. Cohorts mix models if you redeploy during a bucket. Log the model version with each prediction and group by version as well as time.
- Time zones and clock source. Use the timestamp written when the prediction was served, in UTC, not the time the log row was ingested. Ingestion delays shift predictions between buckets.
- Rate comparisons. The positive rate of an immature cohort is lower than its final rate. Never compare label rates across cohorts with different maturity.
What coverage tells you
Coverage from matured_auc answers "how much of recent traffic does this number speak for?" Suppose you serve 10,000 predictions a day and the maturity window is 30 days. On any day, the metric describes traffic from at least 30 days ago. The most recent 30 days, which is the traffic the business cares about now, is not represented at all. This gap is the reason the later chapters cover label-free estimates. Matured-cohort evaluation is the ground truth you eventually reconcile those estimates against, not a replacement for them.
Summary of the method
- Log
id,predicted_at, score and model version for every prediction. - Choose a maturity window from the observed delay distribution.
- Bucket predictions by
predicted_at. - Score a bucket only when its newest prediction is mature.
- Left-join labels, and treat missing labels as negative only where that is true.
- Publish the metric together with
n, status and coverage.
Exercise
A fraud team scores yesterday's predictions each morning by inner-joining the prediction log to all chargebacks received so far. Their reported recall looks excellent, and then drops sharply every time they re-run the number a month later. Give two reasons the original number was misleading, and say how you would change the evaluation.
Show answer
First, the inner join keeps only predictions that already have a chargeback, so the data contains almost no true negatives, and the labeled rows are skewed toward fast-resolving fraud. Second, yesterday's predictions are immature: most of their chargebacks have not arrived, and the ones that have are the quickest to appear, which tend to be the easiest for the model to catch. Recall measured on this sample is inflated. To fix it, group predictions by predicted_at, left-join labels, and score a cohort only after the maturity window has passed, treating missing labels as negative only if that is valid for chargebacks. Report coverage next to the metric, and mark recent cohorts as provisional.
Exercise
You run cohort_report with weekly buckets and a 30-day maturity window. The newest scored cohort is about how many days older than now, at minimum and at most?
Show answer
A cohort is scored only when its newest prediction is at least 30 days old. The newest prediction in a weekly bucket is at most at the end of the week, so the cohort's last day is 30 days old at minimum. Its first day is about 36 days old, since the bucket spans up to seven days. So the freshest scored cohort ends at least 30 days ago and starts up to about 37 days ago. The lag in practice is the window plus up to one bucket width.