Sub topic 9
Estimating Performance from Predicted Probabilities
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 calibration chapter, so you know what "calibrated" means. Here we use calibrated scores to estimate performance on recent predictions before any labels arrive.
The core idea
A classifier that outputs a probability makes a claim about itself. A score of 0.9 says "about 9 in 10 cases like this are positive". If that claim is true, you can compute how often the model is right without seeing a single label.
This is confidence-based performance estimation (CBPE). Treat each score p as the probability that the true label is 1. Then:
- If the model predicts positive (
p >= threshold), it is correct with probabilityp. - If the model predicts negative, it is correct with probability
1 - p.
Averaging these per-row probabilities gives the expected accuracy of the batch. The same reasoning gives expected values for every cell of the confusion matrix, and from those, precision, recall and F1.
Expected accuracy
The simplest case is accuracy.
import numpy as np
def expected_accuracy(p_positive, threshold=0.5):
"""Expected accuracy of a binary classifier, with no labels.
Valid only if p_positive is calibrated: among cases scored p,
a fraction p is truly positive.
"""
p = np.asarray(p_positive, dtype=float)
predicted_positive = p >= threshold
# Probability each prediction is correct under the calibrated assumption.
p_correct = np.where(predicted_positive, p, 1.0 - p)
return float(p_correct.mean())Scores near 0 or 1 contribute almost certain correctness. Scores near the threshold contribute about 0.5. A batch whose scores drift toward the middle therefore gets a lower estimated accuracy, even though no label has arrived. This is the early-warning behavior you want.
Expected confusion matrix and derived metrics
Each row contributes fractional counts to the confusion matrix. For a predicted positive with score p, it adds p to true positives and 1 - p to false positives. For a predicted negative, it adds p to false negatives and 1 - p to true negatives.
import numpy as np
def expected_confusion(p_positive, threshold=0.5):
p = np.asarray(p_positive, dtype=float)
pred_pos = p >= threshold
tp = p[pred_pos].sum()
fp = (1.0 - p[pred_pos]).sum()
fn = p[~pred_pos].sum()
tn = (1.0 - p[~pred_pos]).sum()
return tp, fp, fn, tn
def expected_metrics(p_positive, threshold=0.5):
tp, fp, fn, tn = expected_confusion(p_positive, threshold)
n = tp + fp + fn + tn
precision = tp / (tp + fp) if (tp + fp) > 0 else float("nan")
recall = tp / (tp + fn) if (tp + fn) > 0 else float("nan")
f1 = (2 * precision * recall / (precision + recall)
if precision == precision and recall == recall
and (precision + recall) > 0 else float("nan"))
return {"accuracy": (tp + tn) / n, "precision": precision,
"recall": recall, "f1": f1}
print(expected_metrics([0.95, 0.80, 0.30, 0.10, 0.60]))Precision, recall and F1 are ratios of sums, so they are estimated as ratios of expected counts. This is a close approximation for reasonably large batches. For very small batches, or when positives are rare, the ratio is noisy.
For ROC AUC there is no closed form that is as simple. A practical approach is Monte Carlo. Draw labels from Bernoulli(p) many times, compute AUC for each draw, and average. Use the spread of those AUCs as an uncertainty band.
import numpy as np
from sklearn.metrics import roc_auc_score
def expected_auc(p_positive, n_draws=200, seed=0):
p = np.asarray(p_positive, dtype=float)
rng = np.random.default_rng(seed)
aucs = []
for _ in range(n_draws):
y = rng.binomial(1, p)
if y.min() == y.max(): # AUC is undefined with a single class
continue
aucs.append(roc_auc_score(y, p))
return float(np.mean(aucs)), float(np.std(aucs))How much noise is in the estimate?
Even with perfect calibration, the estimate is not the realized accuracy. Realized accuracy depends on which labels actually turn out positive. Under the calibrated assumption each prediction is a Bernoulli trial with success probability p_correct. The standard error of the batch accuracy is therefore:
import numpy as np
def accuracy_standard_error(p_positive, threshold=0.5):
p = np.asarray(p_positive, dtype=float)
p_correct = np.where(p >= threshold, p, 1.0 - p)
return float(np.sqrt((p_correct * (1.0 - p_correct)).sum()) / len(p))Use this to size batches. A daily batch of 200 rows gives a wide band. A weekly batch of 10,000 rows gives a narrow one. Report the band, not only the point value.
What the estimate assumes
CBPE is only as good as its assumptions. Check each one before you trust a number.
- The scores are calibrated on the data you are scoring. This is the central assumption. Calibration measured on the validation set says nothing guaranteed about this month's traffic.
- The relationship between features and label has not changed. If
P(y | x)shifts (concept drift), the model's scores no longer describe reality, and the estimate stays confident and wrong. - The threshold is the one used in production. Estimate with the decision rule your system actually applies.
- Predictions are independent enough for the error band to mean something. Duplicated or tightly correlated rows make the band too narrow.
Two kinds of change behave differently here:
| Change in production | Does CBPE still work? | Why |
|---|---|---|
| Covariate shift, with `P(y given x)` unchanged and the model calibrated across the new region | Often yes | The scores still describe the true label probability for each input. Uncertain inputs produce lower scores, so the estimate falls. |
| Covariate shift into regions the model never saw | Often no | The model's calibration there is unverified and is usually overconfident. |
| Concept drift, where `P(y given x)` changes | No | The scores describe the old world. |
| Label prior shift (the base rate changes) | Not directly | A model calibrated at a 2% base rate is miscalibrated at 5%. Recalibrate or adjust the prior. |
Seeing the failure on purpose
A simulation makes the dependence on calibration concrete. Below, true_p is the real label probability. The first score set is perfectly calibrated. The second is an overconfident version of the same model: it makes the same decisions but pushes probabilities toward 0 and 1.
import numpy as np
from_logit = lambda z: 1.0 / (1.0 + np.exp(-z))
def expected_accuracy(p_positive, threshold=0.5):
p = np.asarray(p_positive, dtype=float)
p_correct = np.where(p >= threshold, p, 1.0 - p)
return float(p_correct.mean())
rng = np.random.default_rng(0)
true_p = rng.beta(2.0, 2.0, size=50_000)
y = rng.binomial(1, true_p)
calibrated = true_p
clipped = np.clip(true_p, 1e-6, 1 - 1e-6)
overconfident = from_logit(2.0 * np.log(clipped / (1.0 - clipped)))
actual = float(((calibrated >= 0.5) == y).mean())
print("actual accuracy: ", round(actual, 4))
print("estimate, calibrated: ", round(expected_accuracy(calibrated), 4))
print("estimate, overconfident:", round(expected_accuracy(overconfident), 4))Both score sets make identical decisions, so the actual accuracy is the same. The calibrated estimate lands close to it. The overconfident estimate lands clearly above it. The model is no worse, but the estimate is wrong because the scores overstate certainty.
Making it dependable in practice
Follow these steps when you set CBPE up for a real model.
- Calibrate on held-out data and keep the calibrator versioned. Use isotonic or Platt scaling, and apply it before the scores are logged or before estimation.
- Measure calibration on recent matured labels. Compute a reliability table or expected calibration error on the latest cohort whose labels have arrived (see the matured-cohort chapter). If calibration has degraded, the estimate for newer data is suspect.
- Estimate by prediction-time cohort. Compute the estimate per day or week, so it lines up with the matured cohorts you will compare against.
- Report the band and the sample size along with the number.
- Backtest continuously. When labels arrive, compare the old estimate to the realized metric. The next chapters cover this in detail.
Common mistakes
- Using uncalibrated scores. Gradient-boosted trees, random forests and neural networks often output scores that are not probabilities. Do not skip calibration.
- Estimating on the data the calibrator was fit on. The estimate looks perfect on that data by construction. Fit the calibrator on one split and check on another.
- Ignoring rare positives. With a 0.5% base rate, a daily batch may hold only a handful of positives. Precision and recall estimates will be very noisy. Aggregate over longer windows.
- Treating a stable estimate as proof of stability. A flat estimate means the scores are stable. It does not mean the model is still right.
Exercise
A calibrated model scores four predictions as 0.9, 0.8, 0.4 and 0.2, with a threshold of 0.5. What is the expected accuracy? What are the expected true positives and false negatives?
Show answer
Predictions 0.9 and 0.8 are positive calls, correct with probabilities 0.9 and 0.8. Predictions 0.4 and 0.2 are negative calls, correct with probabilities 0.6 and 0.8. The mean is (0.9 + 0.8 + 0.6 + 0.8) / 4 = 3.1 / 4 = 0.775. Expected true positives are 0.9 + 0.8 = 1.7. Expected false negatives are 0.4 + 0.2 = 0.6.
Exercise
Your fraud model's estimated accuracy has been flat at 0.97 for six weeks, but matured-cohort accuracy for the same weeks has fallen from 0.97 to 0.91. Name the most likely cause and one action.
Show answer
The most likely cause is concept drift (a change in P(y given x), for example fraudsters changing tactics) or lost calibration. The model's scores stay confident, so CBPE does not move. Action: check calibration on the matured cohort, for example with a reliability table, and recalibrate on recent labeled data. If the underlying pattern changed, retrain the model.