Sub topic 12
Spending a labeling budget where it helps most
Earlier chapters showed how to estimate performance before labels arrive: matured cohorts, drift signals, calibrated probabilities and importance weights. Sometimes you can also buy labels sooner. An analyst can review a flagged transaction today, a customer can be called, or a loan can be audited. This chapter covers how to spend that limited review capacity so the labels both sharpen your estimate and stay statistically valid.
It assumes you know the following:
- Binary classification metrics.
- Calibrated probabilities, from the calibration and confidence-based estimation chapters.
- The censoring and selection bias problem from earlier in the tutorial.
- Basic pandas.
Why labeling effort needs a design
A labeling budget is a fixed number of labels you can obtain per period, for example 500 manual reviews a week. There are two ways to waste it:
- Labeling at random. Most production traffic is easy. If a fraud model is 99% sure on 95% of transactions, a random sample spends 95% of its labels on cases that are almost never wrong. Your accuracy estimate stays noisy.
- Labeling only the interesting cases. If you review only the least confident predictions, the labeled set is a biased slice. Its accuracy says little about the full population. This is the same selection bias as in partially labeled production data, except you created it yourself.
The goal is to concentrate labels where they reduce uncertainty about your metric, and to record how each row was chosen so you can correct for the choice.
Two goals: estimating and improving
A labeling budget can serve two different purposes, and they call for different sampling.
| Goal | What you want | Good sampling | Weighting needed |
|---|---|---|---|
| Estimate current accuracy or error rate | Low-variance, unbiased metric | Stratified, with allocation by expected error | Yes, by inverse inclusion probability |
| Improve the model (retraining data) | Informative examples | Uncertainty or disagreement sampling | Yes, if you also evaluate on them |
| Detect a failure in a segment | Enough labels per segment | Per-segment quotas | Yes, when combining segments |
This chapter focuses on the first goal. If you reuse the same labels for retraining, keep a separate random slice for evaluation. A sample chosen because the model was unsure is a poor test set.
The principle: known inclusion probabilities
An estimate from a non-random sample is unbiased if you know each row's inclusion probability, which is the chance that the row was selected. You then weight each labeled row by 1 divided by that probability. This is the Horvitz-Thompson idea, and it is the same inverse-weighting logic as importance weighting.
Selection must be randomized with known probabilities, or the weights are not meaningful. "An analyst picked the suspicious ones" has no usable inclusion probability. "Every row in the 0.3 to 0.5 score band had a 12% chance of selection" does.
Stratify by confidence
Stratified sampling is the practical way to do this. Split the scored predictions into strata, which are non-overlapping groups, and sample inside each one. Calibrated confidence is a natural stratifier because it predicts where errors are.
If scores are calibrated, the expected error of a prediction with positive-class probability p is min(p, 1 - p). A stratum with mean expected error near 0 has little to teach you. A stratum near 0.5 is where outcomes are least certain.
The standard allocation rule is Neyman allocation. Give stratum h a number of labels proportional to Nh × σh, where Nh is the stratum size and σh is the standard deviation of correctness inside it. For a 0/1 outcome with error rate m, σ = sqrt(m(1 − m)). Large, uncertain strata get more labels. Large, near-certain strata get fewer, but never zero.
A working implementation
The script below simulates a window of 20,000 calibrated predictions. It allocates 600 labels with Neyman allocation, draws the sample, and estimates accuracy with a standard error. It also reports what a plain random sample of the same size would have given. In production, the y column would not exist until the reviewer returns a label. Here it lets you check the answer.
import numpy as np
import pandas as pd
rng = np.random.default_rng(7)
# Simulated window: calibrated P(y=1) and hidden truth.
n = 20_000
p = rng.beta(0.5, 0.5, size=n)
y = rng.binomial(1, p)
df = pd.DataFrame({"p": p, "pred": (p >= 0.5).astype(int), "y": y})
df["stratum"] = pd.cut(
df["p"], bins=[0, 0.1, 0.3, 0.5, 0.7, 0.9, 1.0],
include_lowest=True, labels=False,
)
def neyman_allocation(frame, budget, min_per_stratum=20):
"""Labels per stratum, proportional to N_h * sd_h of correctness."""
err = np.minimum(frame["p"], 1 - frame["p"])
g = err.groupby(frame["stratum"])
sizes = g.size()
m = g.mean().clip(0.01, 0.99) # avoid zero-variance strata
raw = sizes * np.sqrt(m * (1 - m))
alloc = (budget * raw / raw.sum()).round().astype(int)
alloc = np.maximum(alloc, min_per_stratum)
return np.minimum(alloc, sizes) # cannot label more rows than exist
def draw_sample(frame, alloc, seed):
parts = []
for h, k in alloc.items():
rows = frame[frame["stratum"] == h]
picked = rows.sample(n=int(k), random_state=seed + int(h))
parts.append(picked.assign(incl_prob=k / len(rows)))
return pd.concat(parts)
def stratified_accuracy(sample, sizes):
"""Accuracy estimate and standard error from a stratified sample."""
correct = (sample["pred"] == sample["y"]).astype(float)
g = correct.groupby(sample["stratum"])
n_h, mean_h = g.size(), g.mean()
var_h = g.var(ddof=1).fillna(0.0)
N_h = sizes.loc[n_h.index]
N = N_h.sum()
est = float((N_h * mean_h).sum() / N)
fpc = 1 - n_h / N_h # finite population correction
var = float(((N_h / N) ** 2 * fpc * var_h / n_h).sum())
return est, var ** 0.5
sizes = df.groupby("stratum").size()
alloc = neyman_allocation(df, budget=600)
sample = draw_sample(df, alloc, seed=11)
est, se = stratified_accuracy(sample, sizes)
# Baseline: simple random sample of the same size.
srs = df.sample(n=len(sample), random_state=3)
srs_correct = (srs["pred"] == srs["y"]).astype(float)
srs_se = (srs_correct.var(ddof=1) / len(srs) * (1 - len(srs) / len(df))) ** 0.5
print("labels used :", len(sample))
print("allocation :", alloc.to_dict())
print(f"stratified acc : {est:.4f} +/- {1.96 * se:.4f}")
print(f"random sample acc: {srs_correct.mean():.4f} +/- {1.96 * srs_se:.4f}")
print(f"true accuracy : {(df['pred'] == df['y']).mean():.4f}")Points to notice in the code:
- The
min_per_stratumfloor can push the total slightly above the budget. Reduce the other strata or accept the overshoot, but do not drop a stratum to zero. A zero-label stratum has no estimate, and its weight is undefined. incl_probis stored on every sampled row. Keep it in your label store, because you will need it months later when you backtest.- The stratified standard error is usually smaller than the random one at equal cost, because the confident strata contribute almost no variance. The gain is largest when the error rate is low and unevenly spread across confidence levels.
Keep a random reserve
Neyman allocation depends on calibration. If calibration has drifted, your expected-error numbers are wrong, so the allocation is wrong. The estimate stays unbiased, because you weight by the true inclusion probabilities, but its variance rises.
A defense is to split the budget. For example, spend 20% on a uniform random sample and 80% on the stratified allocation. The random slice gives you:
- A model-free estimate that does not rely on calibration.
- A direct check of whether the confidence-based estimate still holds.
- A fallback if the stratification variable itself breaks, for example after a feature change.
Practical edge cases
- Reviewers do not return every label. If 15% of requested labels never come back, the missing ones may not be random, for example hard cases get skipped. Track the response rate per stratum and treat non-response as another censoring problem.
- Strata change between windows. Keep bin edges fixed over time so period-to-period estimates are comparable. If you change them, note it in the metadata.
- Rare positives. For a 0.5% positive rate, confidence strata may hold only a handful of positives. Add the predicted class as a second stratifier, or oversample predicted positives, since precision depends on them.
- Feedback loops. If the labeled rows are then used for retraining, the model improves exactly where you sampled. This is fine for the model, but keep the evaluation reserve out of training.
- Overlap with natural labels. Some rows get labels without your help, such as chargebacks. Do not double count. Treat the natural arrival as a separate, biased channel, and use the purchased sample, with known probabilities, as the anchor.
What to do with the estimate
The weighted estimate is a ground-truth-based number available days or weeks before the full label delay passes. It is still noisy, so report the interval alongside it. Then do two things:
- Compare it with the label-free estimate from calibrated probabilities. If the two intervals disagree, suspect calibration drift or concept drift.
- Store the sample with its inclusion probabilities, so that when the matured labels arrive you can backtest both estimates against the final truth. The next chapters build on that history.
Exercise
A team labels the 500 least confident predictions each week and reports the accuracy of those rows as "current model accuracy". Give two things wrong with this, and one change that fixes it.
Show answer
First, the sample contains only the hardest cases, so its accuracy is much lower than the accuracy over all traffic, and it is a biased estimate. Second, the selection is deterministic, so no inclusion probabilities exist, and weighting cannot correct the bias. The fix is to select randomly inside confidence strata, for example with Neyman allocation, store each row's inclusion probability, and compute a weighted stratified estimate. A random reserve slice should also be kept as a check.
Exercise
In the script above, a stratum has size 4,000 and 50 labels were drawn from it. What is the inclusion probability and the weight of each labeled row in that stratum, and what does that weight mean?
Show answer
The inclusion probability is 50 / 4000 = 0.0125. The weight is 1 / 0.0125 = 80. Each labeled row stands for 80 rows of that stratum, itself plus 79 unlabeled ones, when computing the population estimate.