Sub topic 5
Censoring and selection bias in partially labeled data
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 earlier chapters on label delay and maturity windows. You will learn how partially labeled production data misleads metrics even after you filter by maturity, and how to detect and reduce that bias.
Two ways labels go missing
Missing labels in production come from two different mechanisms. They need different fixes.
- Censoring is when the outcome has not happened or been observed yet. A loan issued last month has no default label, but it may still default. The label is missing because of time.
- Selection bias is when the labeled rows are not a random sample of all predictions. The model's own decisions, or a business process, decide which rows get labels.
The two often combine. A fraud model blocks some transactions. Blocked transactions never get a chargeback, so you never learn whether they were fraud. The approved ones get labels only after the dispute window passes.
| Mechanism | Why the label is missing | Typical example | Main remedy |
|---|---|---|---|
| Censoring | Outcome not yet observed | Default within 12 months, row is 3 months old | Maturity windows, survival-style analysis |
| Selection by the model | The prediction changed what you could observe | Rejected loan applicants never repay or default | Reweighting, exploration, targeted labeling |
| Selection by process | Only some cases get reviewed | Analysts review only high-score alerts | Random audit sample, reweighting |
Censoring: the "missing means negative" trap
The matured_auc function from the maturity chapter fills missing labels with 0 after the window. That is only safe if the window is long enough that almost all positives have arrived. If the window is too short, late positives are counted as negatives, and the metric is biased.
Consider a default model where 40% of defaults are reported after 90 days. With a 60-day window, those late defaults stay unlabeled and are scored as non-defaults. The model's recall looks worse than it is, and the positive rate in your evaluation set looks lower than the true rate.
The bias has a direction, which helps you reason about it:
- Treating unlabeled rows as negative lowers the observed positive rate.
- High-scoring rows that later turn positive are counted as false positives, so precision is understated.
- Low-scoring rows that later turn positive are counted as true negatives, so recall is overstated or understated depending on how the positives are distributed. Check this case by case.
To see how much censoring you have, plot the cumulative share of positive labels against the age of the prediction. The curve should flatten. The age where it flattens is the lower bound for your maturity window.
import pandas as pd
def label_arrival_curve(preds: pd.DataFrame, labels: pd.DataFrame,
max_days: int = 120, step: int = 10) -> pd.DataFrame:
"""Share of eventual positives that were labeled within N days.
preds: columns id, predicted_at (datetime)
labels: columns id, label, labeled_at (datetime); positives only matter here
"""
pos = labels[labels["label"] == 1].merge(
preds[["id", "predicted_at"]], on="id", how="inner"
)
pos["delay_days"] = (pos["labeled_at"] - pos["predicted_at"]).dt.days
rows = []
for d in range(step, max_days + 1, step):
share = (pos["delay_days"] <= d).mean() if len(pos) else float("nan")
rows.append({"days": d, "share_of_positives_labeled": share})
return pd.DataFrame(rows)The share is computed over positives that have arrived so far, so it is only meaningful for old cohorts. Compute it on cohorts old enough that you believe nearly all labels are in. Otherwise the curve flatters you, because it cannot count labels that have not yet arrived.
Selection bias: the model shapes its own labels
Selection bias is harder to see because the labeled rows can look healthy. Three common sources:
- Decision-gated outcomes. Only approved loans have repayment outcomes. A model trained and evaluated on approved loans never sees how rejected applicants would have behaved.
- Review-gated outcomes. Analysts check alerts above a score threshold. Labels exist mostly for high scores, so a metric computed on labeled rows says little about low-score rows.
- Response-gated outcomes. In churn work, you may only learn the outcome for customers you contacted, and contact was targeted by an earlier model.
In all three cases, the probability that a row is labeled depends on the features or the score. In statistical terms, labels are not missing at random. A simple estimate on the labeled subset converges to the wrong number, no matter how much data you collect.
A small demonstration
The simulation below labels only rows with a score above 0.5. It then compares AUC on all rows with AUC on the labeled subset. The two usually differ, because the labeled subset excludes the easy negatives at low scores.
import numpy as np
from sklearn.metrics import roc_auc_score
rng = np.random.default_rng(0)
n = 20000
score = rng.uniform(0, 1, n)
# True outcome depends on the score, so the model is informative.
y = rng.binomial(1, 0.1 + 0.6 * score)
labeled = score > 0.5 # only high scores get reviewed
auc_all = roc_auc_score(y, score)
auc_labeled = roc_auc_score(y[labeled], score[labeled])
print(f"AUC on all rows: {auc_all:.3f}")
print(f"AUC on labeled rows: {auc_labeled:.3f}")
print(f"Labeled share: {labeled.mean():.2%}")The labeled-subset AUC is lower, because the model's ranking is only being tested over a narrow score range. Accuracy at a fixed threshold would show a different distortion. The point is that the same model gives different numbers depending on which rows have labels.
Detecting the problem
You cannot measure bias in labels you do not have, but you can look for signs.
- Labeling rate by score band. Group predictions into score deciles and compute the share of each decile with a label. A flat rate suggests labeling is unrelated to score. A steep rate means selection depends on the model.
- Labeling rate by feature. Do the same for key features such as region, product, or customer segment.
- Positive rate among labeled rows versus the known base rate. If an independent source gives the true event rate, compare it with your labeled rate.
- Policy change dates. Changes in thresholds, review staffing, or approval rules shift which rows get labels. Mark them on your metric charts.
import pandas as pd
def labeling_rate_by_score(df: pd.DataFrame, bins: int = 10) -> pd.DataFrame:
"""df columns: score, has_label (bool). Returns label rate per score bin."""
out = df.copy()
out["score_bin"] = pd.qcut(out["score"], q=bins, duplicates="drop")
return (
out.groupby("score_bin", observed=True)["has_label"]
.agg(label_rate="mean", rows="size")
.reset_index()
)Reducing the bias
No method removes selection bias without assumptions. Each option trades cost against how much you must trust the assumption.
Reweight by the probability of being labeled
If labeling depends only on features you observe, you can estimate the probability that a row is labeled and weight each labeled row by the inverse of that probability. This is inverse probability weighting. It uses the same idea as the importance weighting chapter: make the labeled rows look like all rows.
The assumption is that, given the features, being labeled is independent of the outcome. If analysts use information that is not in your features, the assumption fails. Also clip large weights. Rows with a labeling probability near zero produce huge weights and unstable estimates. If a score region has no labels at all, no weighting can recover it.
Keep a random audit sample
The most reliable fix is to label a small random sample of rows that would normally go unlabeled. For example, approve a random 1% of applications that the model would reject, or have analysts review 1% of low-score alerts. This gives unbiased labels in the regions you would otherwise never see. The cost is real: you may approve bad loans or let fraud through. Size the sample to the loss you can accept, and record the sampling probability for every row so you can weight the audit rows correctly.
Choose a longer window or a model of delay
For censoring alone, a longer maturity window is the simplest fix, at the cost of slower feedback. When the cost is too high, survival analysis methods model the time to event and use partially observed rows correctly. These are beyond this chapter, but they let you use young rows without calling them negative.
Report coverage and label what you did
Whatever you choose, report the labeled share and the filters applied alongside every metric. A reader who sees "AUC 0.91, 8% of rows labeled, labels only for score above 0.5" can judge the number. A bare "AUC 0.91" is misleading.
Common errors
- Using a maturity window shorter than the plateau of the label arrival curve.
- Comparing metrics before and after a threshold change without noting that the labeled population changed.
- Training a replacement model only on labeled rows and then evaluating it only on labeled rows. Both inherit the same selection.
- Computing inverse weights from a model that sees features the labeling process did not use, or the reverse.
- Reporting a metric without its coverage.
Exercise
A loan default model rejects applicants with a score above 0.7. Repayment outcomes exist only for approved applicants. A teammate reports that accuracy on all labeled loans is 96% and says the model is performing well. Name the bias, say which score range has no labels, and propose one fix with its cost.
Show answer
This is selection bias created by the model's own decisions. No labels exist for applicants scored above 0.7, so the 96% figure says nothing about the high-risk region where the model's rejections matter most. One fix is to approve a small random sample (for example 1%) of applicants who would be rejected, record that sampling rate, and use those outcomes to estimate performance in the high-score region with weights. The cost is the expected losses on the extra approved loans. Inverse probability weighting would not help here, because the labeling probability is zero above 0.7.
Exercise
Your label arrival curve shows 85% of eventual positives labeled by day 30, 95% by day 60, and 99% by day 90. You use a 30-day maturity window and fill missing labels with 0. In which direction is the observed recall of the positive class biased, and what would you change?
Show answer
Positives that arrive after day 30 are scored as negatives, so about 15% of true positives are treated as negatives. For the positive class, the measured positive rate is too low, and the high-score rows that later turn positive count as false positives, so precision is understated. Recall is computed against the labeled positives only, so its bias depends on how the missed positives were scored. Move the window to at least 60 days (95% complete), or 90 days if the cost of a miss is high, and report coverage so readers know how stale the metric is.