Sub topic 15
When calibration breaks: distribution shift and monitoring
This chapter assumes you can fit a calibrator with CalibratedClassifierCV, read a reliability diagram, and compute Brier score and expected calibration error (ECE). It also assumes you know the sigmoid and the logit (log-odds) function. The question here is what happens after deployment, when the data no longer looks like the data you calibrated on.
Why a calibrator expires
A calibrator learns a mapping from model scores to probabilities. It is fitted on one data distribution, and it is correct only for that distribution. If the mix of inputs or labels changes, the mapping can be wrong even though the model still ranks cases well.
This is why calibration and discrimination can diverge in production. AUC depends only on the ordering of scores, so a monotone shift in the scores leaves it untouched. ECE and Brier score depend on the actual values, so they move.
Three kinds of shift
Name the shift before choosing a response. Each one breaks calibration differently.
| Shift | What changes | Effect on calibration | Typical response |
|---|---|---|---|
| Covariate shift | The distribution of inputs `P(x)`. `P(y given x)` is unchanged. | Often small where the model was well fitted. Large in regions with little training data, where the model extrapolates. | Detect with input drift checks. Recalibrate on recent labeled data if needed. |
| Prior (label) shift | The base rate `P(y)`. `P(x given y)` is unchanged. | Probabilities are systematically too high or too low. | Adjust the odds by the ratio of new to old priors, or recalibrate. |
| Concept shift | The relationship `P(y given x)` itself | Both ranking and calibration can degrade. | Retrain. Recalibration alone rarely suffices. |
Real drift is usually a mix. Treat the table as a diagnostic checklist, not a classification you can always achieve.
Seeing the failure: prior shift
The script below calibrates a logistic regression with sigmoid calibration, then evaluates it on two sets. One set comes from the training distribution. The other is resampled so that only 10% of cases are positive. The class-conditional feature distributions are unchanged, so this is pure prior shift.
The script then applies a prior correction. For a probability p from a model trained with prior pi_old, the adjusted odds are p/(1-p) multiplied by (pi_new/(1-pi_new)) / (pi_old/(1-pi_old)).
import numpy as np
from sklearn.calibration import CalibratedClassifierCV
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import brier_score_loss, roc_auc_score
from sklearn.model_selection import train_test_split
def expected_calibration_error(y_true, y_prob, n_bins=10):
y_true = np.asarray(y_true)
y_prob = np.asarray(y_prob)
edges = np.linspace(0.0, 1.0, n_bins + 1)
bin_ids = np.digitize(y_prob, edges[1:-1], right=True)
ece = 0.0
for b in range(n_bins):
mask = bin_ids == b
if mask.any():
ece += mask.mean() * abs(y_true[mask].mean() - y_prob[mask].mean())
return ece
def adjust_for_prior_shift(p, old_prior, new_prior):
p = np.clip(p, 1e-12, 1 - 1e-12)
odds = p / (1 - p)
odds *= (new_prior / (1 - new_prior)) / (old_prior / (1 - old_prior))
return odds / (1 + odds)
def report(name, y, p):
print(
f"{name:<22} mean p={p.mean():.3f} rate={y.mean():.3f} "
f"ECE={expected_calibration_error(y, p):.3f} "
f"Brier={brier_score_loss(y, p):.3f} AUC={roc_auc_score(y, p):.3f}"
)
X, y = make_classification(
n_samples=40000, n_features=20, n_informative=5, n_redundant=10,
flip_y=0.05, random_state=0,
)
X_train, X_rest, y_train, y_rest = train_test_split(X, y, test_size=0.5, random_state=0)
model = CalibratedClassifierCV(LogisticRegression(max_iter=1000), method="sigmoid", cv=5)
model.fit(X_train, y_train)
rng = np.random.default_rng(0)
pos = np.flatnonzero(y_rest == 1)
neg = np.flatnonzero(y_rest == 0)
n_pos = int(len(neg) * 0.10 / 0.90)
keep = np.concatenate([neg, rng.choice(pos, size=n_pos, replace=False)])
X_shift, y_shift = X_rest[keep], y_rest[keep]
p_same = model.predict_proba(X_rest)[:, 1]
p_shift = model.predict_proba(X_shift)[:, 1]
p_fixed = adjust_for_prior_shift(p_shift, y_train.mean(), y_shift.mean())
report("same distribution", y_rest, p_same)
report("prior shift", y_shift, p_shift)
report("prior shift, adjusted", y_shift, p_fixed)Expect the AUC to stay about the same across all three rows. The ECE and Brier score should worsen on the shifted set, and the mean predicted probability should sit well above the new 10% positive rate. The adjusted row should recover most of the loss.
The adjustment needs the new prior. You often do not have it without labels. You can estimate it from a small labeled sample, or with methods such as expectation maximization on the unlabeled scores, but both depend on the prior-shift assumption actually holding.
Covariate shift and the extrapolation problem
Under covariate shift, P(y given x) is stable, so a model that has learned it should stay calibrated. In practice calibrators fail in two ways.
- Sparse regions. Isotonic regression is a step function fitted to the score range it saw. Scores outside that range get the value of the nearest step. In a new region the true rates may differ, and the calibrator cannot know.
- Misspecified base model. If the model is only approximately right, its errors are concentrated where it had little data. Inputs that move into those regions bring the errors with them.
Input drift tests (population stability index, Kolmogorov-Smirnov on key features or on the score) tell you that something moved. They do not tell you whether calibration got worse. Use them as an early warning, then confirm with labels.
Monitoring with labels
The reliable signal is measured calibration on recent labeled outcomes. Track these quantities per time window:
- Mean predicted probability against observed rate. This is calibration-in-the-large and the cheapest check. A gap points to prior shift.
- Calibration intercept and slope. Fit a logistic regression of the outcome on the logit of the predicted probability. Perfect calibration gives intercept 0 and slope 1. A nonzero intercept means a systematic offset. A slope below 1 means the model is overconfident.
- Brier score and log loss. Compare them to the values from your validation set.
- ECE. Use it with caution on small windows, because binning noise is large.
The next script simulates weekly batches where the model's logits drift upward by 0.2 per week, and flags weeks where the intercept leaves a tolerance band.
import numpy as np
from scipy.special import expit, logit
from sklearn.linear_model import LogisticRegression
def intercept_and_slope(y, p):
z = logit(np.clip(p, 1e-6, 1 - 1e-6)).reshape(-1, 1)
fit = LogisticRegression(C=1e6, max_iter=1000).fit(z, y)
return float(fit.intercept_[0]), float(fit.coef_[0, 0])
rng = np.random.default_rng(1)
n = 3000
for week in range(6):
z = rng.normal(0.0, 1.5, size=n)
y = (rng.random(n) < expit(z)).astype(int)
p_model = expit(z + 0.2 * week)
intercept, slope = intercept_and_slope(y, p_model)
flag = "ALERT" if abs(intercept) > 0.25 else "ok"
print(
f"week {week}: mean p={p_model.mean():.3f} rate={y.mean():.3f} "
f"intercept={intercept:+.2f} slope={slope:.2f} {flag}"
)The slope stays near 1 because the drift here is a pure offset. The intercept moves by about -0.2 per week and crosses the alert band around week 2. Choose the band from the sampling noise of your window size, not from a round number.
Deciding what to do
A stable AUC with bad calibration is the case recalibration handles well. A dropped AUC means the ranking itself is worse, and no monotone mapping repairs that.
Practical rules
- Store the calibration data's date range, base rate, and metrics with the model. You need them as the baseline for every later comparison.
- Expect labels to arrive late. Loan defaults or churn may take months. Monitor score distributions meanwhile, and treat them as indirect evidence only.
- Evaluate on slices, such as region or customer segment. Global calibration can look fine while one subgroup is badly off.
- Use the same ECE binning in every window, and report window size next to it. An ECE computed on 200 rows and one on 20,000 rows are not comparable.
- Set a retrain or recalibrate policy ahead of time, with thresholds and an owner, so alerts lead to action.
Exercise
A fraud model was calibrated when 2% of transactions were fraudulent. A month later the fraud rate is 4%, and the feature distributions within each class are unchanged. AUC is unchanged. Do the model's probabilities become too high or too low, and what is the cheapest fix?
Show answer
They become too low, because the model still assumes fraud is rare, so it underestimates the probability of fraud. This is prior shift. The cheapest fix is to multiply each prediction's odds by (0.04/0.96) / (0.02/0.98), about 2.04, and convert back to probabilities. This works only if the new prior is known or reliably estimated and the within-class feature distributions really are stable. Otherwise recalibrate on recent labeled data.
Exercise
In the weekly monitoring script, the intercept stays near 0 but the slope falls from 1.0 to 0.7. What does that say about the model, and would a prior adjustment fix it?
Show answer
A slope below 1 means the predicted logits are too spread out, so the model is overconfident: high scores are too high and low scores are too low, even though the average is right. A prior adjustment only shifts all logits by a constant, so it cannot fix this. Use a calibrator that rescales, such as Platt scaling or temperature scaling, fitted on recent labeled data. If AUC also fell, retrain.