Sub topic 11
Learning to Predict the Model's Own Error
This chapter assumes you know binary classification metrics, pandas and scikit-learn, and how a prediction log is structured. It also assumes you have read the earlier chapters on matured cohorts, calibration, probability-based estimation and importance weighting. Those chapters give you two ways to estimate performance without fresh labels. Both break down in some settings, and this chapter covers a third option for those settings.
The idea
Confidence-based estimation reads the model's own probabilities and trusts them. Importance weighting reuses labeled reference rows and trusts that only the feature distribution moved. A third option is to train a second model, the error model, whose job is to predict how wrong the primary model will be on each row.
The setup has four steps:
- Collect rows where you have both the primary model's prediction and the true label.
- Compute a per-row loss for each row, such as 0/1 error, squared error, or log loss.
- Train the error model to predict that loss from the row's features and the primary model's output.
- Apply the error model to new, unlabeled rows. The mean predicted loss is your performance estimate.
Because you only need the mean, the error model does not have to be right about any single row. It has to be right on average over a cohort.
When it beats the alternatives
The error model sits between the two methods you already know.
| Method | What it trusts | Typical failure |
|---|---|---|
| Probability-based estimate | The primary model's probabilities are calibrated on new data | Calibration breaks under shift |
| Importance weighting | Only P(x) changed, and the density ratio is estimable | Extreme weights, little overlap between reference and new data |
| Error model | The relationship between (x, score) and error carries over to new rows | Extrapolation into regions the reference data never covered |
The error model needs no calibrated scores. It can learn that the model is overconfident in a certain region and correct for it. It also handles several metrics from one framework, because you choose the per-row loss. The cost is that you now have a second model to train, validate, and maintain.
A runnable example
This script builds a primary classifier, creates a covariate-shifted "new" set by sampling with a bias on one feature, and estimates the new error rate with an error model. It then compares the estimate with the true value. In real monitoring you would not have y_new yet. It is used here only to check the result.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.ensemble import GradientBoostingClassifier, HistGradientBoostingClassifier
from sklearn.metrics import brier_score_loss
from sklearn.model_selection import cross_val_predict
rng = np.random.default_rng(0)
X, y = make_classification(
n_samples=9000, n_features=10, n_informative=5,
flip_y=0.05, class_sep=0.8, random_state=0,
)
# The primary model trains on the first 3000 rows.
X_train, y_train = X[:3000], y[:3000]
X_pool, y_pool = X[3000:], y[3000:]
# Covariate shift: new rows are sampled with a bias toward high feature 0.
# P(y | x) is untouched, because we only choose which rows appear.
weights = 1.0 / (1.0 + np.exp(-2.0 * X_pool[:, 0]))
weights /= weights.sum()
new_idx = rng.choice(len(X_pool), size=1500, replace=False, p=weights)
is_new = np.zeros(len(X_pool), dtype=bool)
is_new[new_idx] = True
X_new, y_new = X_pool[is_new], y_pool[is_new]
X_ref, y_ref = X_pool[~is_new], y_pool[~is_new]
primary = GradientBoostingClassifier(random_state=0).fit(X_train, y_train)
def error_features(X_rows, scores):
"""The error model sees the raw features and the primary model's score."""
return np.column_stack([X_rows, scores])
p_ref = primary.predict_proba(X_ref)[:, 1]
p_new = primary.predict_proba(X_new)[:, 1]
# Per-row 0/1 error on labeled reference rows (held out from primary training).
err_ref = ((p_ref >= 0.5).astype(int) != y_ref).astype(int)
Z_ref = error_features(X_ref, p_ref)
Z_new = error_features(X_new, p_new)
error_model = HistGradientBoostingClassifier(
max_depth=3, learning_rate=0.05, max_iter=150, random_state=0
)
# Check the error model with out-of-fold predictions before trusting it.
oof = cross_val_predict(error_model, Z_ref, err_ref, cv=5, method="predict_proba")[:, 1]
baseline = np.full_like(oof, err_ref.mean(), dtype=float)
print("Brier, error model :", round(brier_score_loss(err_ref, oof), 4))
print("Brier, constant :", round(brier_score_loss(err_ref, baseline), 4))
error_model.fit(Z_ref, err_ref)
estimated_error = error_model.predict_proba(Z_new)[:, 1].mean()
true_error = ((p_new >= 0.5).astype(int) != y_new).mean()
print("Reference error (naive) :", round(err_ref.mean(), 4))
print("Estimated new error :", round(float(estimated_error), 4))
print("True new error :", round(float(true_error), 4))Read the output in two steps. First, the error model's out-of-fold Brier score should beat the constant baseline. If it does not, the error model has found no signal, and its estimate is no better than the reference average. Second, compare the estimated new error with the naive reference error. Under real shift the true error moves, and a useful error model moves with it.
Design decisions
Train the error model on data the primary model has not seen
The primary model fits its own training rows, so its error there is close to zero and unrepresentative. If you train the error model on those rows, it learns that the model is almost never wrong. Use a held-out labeled set, or matured production cohorts. If you must use training data, use out-of-fold predictions from cross-validation.
Choose the loss for the metric you need
The mean of a per-row loss gives you a dataset-level metric directly. It works for any metric that is an average over rows.
- 0/1 error gives accuracy, as one minus the mean.
- Squared error between the score and the label gives the Brier score.
- Log loss gives the cross-entropy.
- Precision, recall and AUC are not row averages. Estimate them indirectly. One way is to estimate the confusion-matrix cells as sums of predicted per-row probabilities of each outcome.
Predict the probability of error, not a hard label
For 0/1 error, train a classifier and average predict_proba, as above. Averaging hard 0/1 predictions of an error classifier is badly biased, because the model rarely predicts "error" even when the error rate is 15%. If the loss is continuous, train a regressor and average its predictions.
Include the primary score as a feature
The score is usually the strongest signal about the error. Rows near the decision threshold fail more often. Including the score lets the error model refine the primary model's confidence rather than rediscover it from the features. It also means the error model generalizes partly like a recalibration, which links it back to the earlier chapters.
Keep the error model simple
A deep error model can memorize noise in a few thousand rows. It can also extrapolate wildly on rows that look unlike the reference data. Shallow trees, strong regularization, and a monotone constraint on the score are reasonable defaults.
Failure modes
The error model is only as good as the stability of the mapping it learned. These are the cases where it fails without warning.
- Concept drift. If P(y | x) changes, the learned mapping from (x, score) to error is stale. The error model sees the new features and predicts the old error pattern. A shift of this kind is invisible to every label-free method, and this one is no exception.
- No overlap. If new rows fall in regions with no reference rows, the error model extrapolates. Tree models then return the error of the nearest leaf, which can be a confident, wrong answer. Check overlap with the domain classifier from the importance-weighting chapter and report the share of new rows outside the reference support.
- Biased training labels. If your labeled rows come from censored or selected data, the error model inherits that bias. A fraud model trained only on cases that were investigated learns the error pattern of investigated cases.
- Feedback loops. If the primary model's decisions change who gets labeled, the error model is learning from its own influence.
- Staleness. The error model is a model, so it drifts. Retrain it on recent matured cohorts on a schedule and backtest it, as covered in the chapter on backtesting estimates.
Where it fits in a monitoring stack
Treat the error model as one estimator among several. Run the probability-based estimate, the importance-weighted estimate, and the error-model estimate on the same new cohort. When all three agree, confidence is high. When they disagree, the pattern is informative. A probability-based estimate that differs from the error-model estimate suggests the scores have lost calibration. An importance-weighted estimate that differs from both suggests overlap problems or unstable weights. Later chapters use these disagreements to decide when an alert should fire.
Exercise
You train an error model on the primary model's own training rows and find its estimated error on new data is 1%, far below the 12% error seen on the validation set. What is the most likely cause, and how do you fix it?
Show answer
The primary model has nearly memorized its training rows, so the per-row error there is close to zero, and the error model learned that the primary model is almost never wrong. Retrain the error model on labeled rows the primary model did not see, such as the validation set or matured production cohorts. If only training rows are available, use out-of-fold predictions from cross-validation to compute the per-row losses.
Exercise
An error model is trained to output a hard 0/1 label for "primary model is wrong", and you estimate error as the mean of those hard outputs. The result is 3% when the true error rate is 15%. Why, and what should you change?
Show answer
Error is the minority outcome for every row, so a classifier rarely crosses 0.5 for the "wrong" class and the mean of its hard outputs undercounts errors. Average the predicted probability of error (predict_proba) instead of the thresholded label. For continuous losses, use a regressor and average its predictions.