TExcelTAD

Distribution Shift

Every evaluation in this course rests on one assumption: the test data comes from the same distribution as the data the model will meet. In production that assumption wears out. A bank enters a new market, a hospital buys a new scanner, prices rise, a pandemic changes behaviour, a fraud ring changes tactics. When the joint distribution P(x,y)P(\mathbf{x}, y) of the deployment data differs from that of the training data, the test score no longer predicts the real one. This lesson names the kinds of shift, shows how to detect them, and two corrections that work when the kind of shift is known. Detecting shift continuously after deployment (drift monitoring) is part of the MLOps course.

Three kinds of shift

Write the joint distribution in two ways, P(x,y)=P(y∣x) P(x)=P(x∣y) P(y)P(\mathbf{x}, y) = P(y \mid \mathbf{x})\, P(\mathbf{x}) = P(\mathbf{x} \mid y)\, P(y). Each kind of shift changes one factor and keeps the other:

Shift What changes What stays Example
Covariate shift P(x)P(\mathbf{x}) P(y∣x)P(y \mid \mathbf{x}) a new age group of customers; images from a darker camera
Label (prior) shift P(y)P(y) P(x∣y)P(\mathbf{x} \mid y) a disease becomes more common; fraud rate rises in December
Concept shift P(y∣x)P(y \mid \mathbf{x}) P(x)P(\mathbf{x}) the definition of spam changes; a policy changes who repays

Covariate shift hurts most when the model is misspecified and the new inputs fall where it was poorly fitted or never trained. Label shift breaks the probabilities and the precision of a model that is otherwise fine (Class Imbalance). Concept shift means the model learned a rule that is no longer true, and only new labels reveal it.

Covariate shift: effect and detection

Training data has a feature x1x_1 around 0; the deployment data has it around 1.5. The true relation is non-linear, a linear model approximates it well near 0 only. Two detectors that need no labels: a per-feature Kolmogorov-Smirnov test, and a domain classifier trained to tell training rows from deployment rows. If it cannot (AUC≈0.5\text{AUC} \approx 0.5), the inputs look alike.

python · try it yourself
import numpy as np
from scipy.stats import ks_2samp
from sklearn.linear_model import LinearRegression, LogisticRegression
from sklearn.model_selection import cross_val_predict, StratifiedKFold
from sklearn.metrics import roc_auc_score

rng = np.random.default_rng(0)
truth = lambda X: 2 * np.sin(X[:, 0]) + 0.5 * X[:, 1]
X_tr = rng.normal(0, 1, (2000, 2))
X_test = rng.normal(0, 1, (1000, 2))                              # same distribution
X_prod = np.column_stack([rng.normal(1.5, 1, 1000), rng.normal(0, 1, 1000)])   # x1 shifted
y_tr, y_test, y_prod = (truth(A) + rng.normal(0, 0.3, len(A)) for A in (X_tr, X_test, X_prod))

model = LinearRegression().fit(X_tr, y_tr)
mse = lambda X, y: np.mean((model.predict(X) - y) ** 2)
print(f"MSE on the test set {mse(X_test, y_test):.3f}, on deployment data {mse(X_prod, y_prod):.3f}")

for j in range(2):
    ks = ks_2samp(X_tr[:, j], X_prod[:, j])
    print(f"KS test feature x{j + 1}: statistic {ks.statistic:.3f}, p-value {ks.pvalue:.2g}")

def domain_auc(A, B):
    Z = np.vstack([A, B]); d = np.r_[np.zeros(len(A)), np.ones(len(B))]
    p = cross_val_predict(LogisticRegression(), Z, d, cv=StratifiedKFold(5, shuffle=True, random_state=0),
                          method="predict_proba")[:, 1]
    return roc_auc_score(d, p)
print(f"domain classifier AUC: train vs test {domain_auc(X_tr, X_test):.3f}, train vs deployment {domain_auc(X_tr, X_prod):.3f}")
MSE on the test set 0.328, on deployment data 2.685
KS test feature x1: statistic 0.556, p-value 7.9e-191
KS test feature x2: statistic 0.038, p-value 0.29
domain classifier AUC: train vs test 0.493, train vs deployment 0.858

The test set says MSE 0.328; on deployment data it is 2.685, eight times worse, though nothing about the model changed. The detectors find the cause without a single deployment label: the KS statistic of x1x_1 is 0.556 with a vanishing p-value, while x2x_2 (0.038, p=0.29p = 0.29) is unchanged; the domain classifier scores 0.493 on train vs test (indistinguishable, as it should be) and 0.858 on train vs deployment. With many features, the domain classifier is the better single alarm: it catches changes in the joint distribution that per-feature tests miss, and its most important features say where the shift is. A tiny p-value with a big sample can flag a harmless shift, so look at the size of the change (the KS statistic) too.

Correcting covariate shift: importance weighting

Under pure covariate shift P(y∣x)P(y \mid \mathbf{x}) is unchanged, so the deployment risk can be rewritten as a training-set average with weights:

Eprod[L]=Etrain[pprod(x)ptrain(x) L],w(x)=pprod(x)ptrain(x)=P(prod∣x)P(train∣x)⋅ntrainnprod\mathbb{E}_{\text{prod}}\big[L\big] = \mathbb{E}_{\text{train}}\left[\frac{p_{\text{prod}}(\mathbf{x})}{p_{\text{train}}(\mathbf{x})}\, L\right], \qquad w(\mathbf{x}) = \frac{p_{\text{prod}}(\mathbf{x})}{p_{\text{train}}(\mathbf{x})} = \frac{P(\text{prod} \mid \mathbf{x})}{P(\text{train} \mid \mathbf{x})} \cdot \frac{n_{\text{train}}}{n_{\text{prod}}}

The density ratio comes for free from the domain classifier's probabilities. Training with these weights makes the model fit best where the deployment data lives:

python · try it yourself
import numpy as np
from sklearn.linear_model import LinearRegression, LogisticRegression

rng = np.random.default_rng(0)
truth = lambda X: 2 * np.sin(X[:, 0]) + 0.5 * X[:, 1]
X_tr = rng.normal(0, 1, (2000, 2))
X_test = rng.normal(0, 1, (1000, 2))
X_prod = np.column_stack([rng.normal(1.5, 1, 1000), rng.normal(0, 1, 1000)])
y_tr, y_test, y_prod = (truth(A) + rng.normal(0, 0.3, len(A)) for A in (X_tr, X_test, X_prod))

# density ratio from a domain classifier fitted on unlabelled deployment inputs
dom = LogisticRegression().fit(np.vstack([X_tr, X_prod]), np.r_[np.zeros(2000), np.ones(1000)])
q = dom.predict_proba(X_tr)[:, 1]
w = q / (1 - q) * (2000 / 1000)
print(f"weights: min {w.min():.3f}, median {np.median(w):.3f}, max {w.max():.1f}")
print(f"effective sample size {w.sum() ** 2 / (w ** 2).sum():.0f} of 2000")

for name, sw in [("unweighted", None), ("importance-weighted", w)]:
    m = LinearRegression().fit(X_tr, y_tr, sample_weight=sw)
    print(f"{name:20s} MSE test {np.mean((m.predict(X_test) - y_test) ** 2):.3f}"
          f"  deployment {np.mean((m.predict(X_prod) - y_prod) ** 2):.3f}")
weights: min 0.001, median 0.311, max 25.6
effective sample size 376 of 2000
unweighted           MSE test 0.328  deployment 2.685
importance-weighted  MSE test 1.239  deployment 1.148

Reweighting cut the deployment MSE from 2.685 to 1.148 and, as the price, raised the error on the original distribution from 0.328 to 1.239: the linear model now fits the region around x1=1.5x_1 = 1.5 instead of 0. The weights range from 0.001 to 25.6, and the effective sample size (∑w)2/∑w2(\sum w)^2 / \sum w^2 is 376 of 2000: most training rows barely count, so the weighted fit is noisier. Importance weighting cannot fix a model that is wrong everywhere; here a flexible model (a forest or boosting, which can follow the sine) would reduce both errors. Weighting helps most for models that must trade accuracy between regions.

Label shift: correcting the prior

If only the class proportions change, from π\pi in training to π′\pi' in deployment, Bayes' rule gives the corrected probability without retraining:

p′(y=1∣x)=p(y=1∣x) π′πp(y=1∣x) π′π+(1−p(y=1∣x)) 1−π′1−π.p'(y = 1 \mid \mathbf{x}) = \frac{p(y = 1 \mid \mathbf{x})\, \frac{\pi'}{\pi}}{p(y = 1 \mid \mathbf{x})\, \frac{\pi'}{\pi} + \big(1 - p(y = 1 \mid \mathbf{x})\big)\, \frac{1 - \pi'}{1 - \pi}} .

When π′\pi' is unknown, it can be estimated from unlabelled deployment data. Two classic estimators: a short EM loop (Saerens et al., 2002) that corrects the probabilities with the current guess of π′\pi', sets π′\pi' to their mean and repeats; and the adjusted count, which takes the share qq of deployment rows the model calls positive and undoes the classifier's known error rates, π^′=(q−FPR)/(TPR−FPR)\hat{\pi}' = (q - \text{FPR}) / (\text{TPR} - \text{FPR}), with TPR and FPR measured on held-out training-side data.

python · try it yourself
import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import log_loss, accuracy_score

X, y = make_classification(n_samples=20000, n_features=8, n_informative=4, weights=[0.5],
                           class_sep=2.0, random_state=0)
X_tr, y_tr = X[:4000], y[:4000]                                   # training: about 50 % positives
rest_pos, rest_neg = np.flatnonzero(y[4000:] == 1) + 4000, np.flatnonzero(y[4000:] == 0) + 4000
deploy = np.r_[rest_pos[:600], rest_neg[:5400]]                   # deployment: 10 % positives
X_dep, y_dep = X[deploy], y[deploy]

X_fit, y_fit, X_val, y_val = X_tr[:3000], y_tr[:3000], X_tr[3000:], y_tr[3000:]
model = LogisticRegression().fit(X_fit, y_fit)
p = model.predict_proba(X_dep)[:, 1]
pi = y_fit.mean()

def correct(p, pi, pi_new):
    a, b = p * pi_new / pi, (1 - p) * (1 - pi_new) / (1 - pi)
    return a / (a + b)

pi_em = pi
for _ in range(50):                                               # EM estimate of the new prior
    pi_em = correct(p, pi, pi_em).mean()
pred_val = model.predict(X_val)                                   # adjusted count: needs TPR, FPR from
tpr, fpr = pred_val[y_val == 1].mean(), pred_val[y_val == 0].mean()   # held-out training-side data
pi_acc = (np.mean(p >= 0.5) - fpr) / (tpr - fpr)
print(f"training prior {pi:.3f}, true deployment prior {y_dep.mean():.3f}")
print(f"estimates: mean probability {p.mean():.3f}, EM {pi_em:.3f}, adjusted count {pi_acc:.3f}")
for name, q in [("uncorrected", p), ("corrected, true prior", correct(p, pi, 0.1)),
                ("corrected, EM", correct(p, pi, pi_em)), ("corrected, adjusted count", correct(p, pi, pi_acc))]:
    print(f"{name:26s} log loss {log_loss(y_dep, q):.3f}  accuracy {accuracy_score(y_dep, q >= 0.5):.3f}")
training prior 0.492, true deployment prior 0.100
estimates: mean probability 0.298, EM 0.073, adjusted count 0.073
uncorrected                log loss 0.375  accuracy 0.845
corrected, true prior      log loss 0.199  accuracy 0.925
corrected, EM              log loss 0.206  accuracy 0.919
corrected, adjusted count  log loss 0.206  accuracy 0.919

The model was trained with 49 % positives, and its mean predicted probability on deployment data is 0.298 where the truth is 0.100: uncorrected, it raises far too many alarms (accuracy 0.845). Correcting with the true prior halves the log loss (0.375 to 0.199) and lifts accuracy to 0.925. Both label-free estimates land at 0.073, below the true 0.100 (estimating a prior from 6000 unlabelled rows with an imperfect classifier is noisy, and EM also assumes calibrated probabilities), yet the corrections with them recover almost all of the gain: log loss 0.206 and accuracy 0.919.

Concept shift: invisible without labels

Now the inputs keep their distribution but the rule changes: in deployment, the label depends on the features in a different way (here, the weight of x2x_2 flips sign). The label-free detectors see nothing:

python · try it yourself
import numpy as np
from scipy.stats import ks_2samp
from sklearn.linear_model import LogisticRegression

rng = np.random.default_rng(1)
sig = lambda z: 1 / (1 + np.exp(-z))
X_tr, X_new = rng.normal(size=(3000, 2)), rng.normal(size=(3000, 2))
y_tr = (rng.random(3000) < sig(2 * X_tr[:, 0] + 1.5 * X_tr[:, 1])).astype(int)
y_new = (rng.random(3000) < sig(2 * X_new[:, 0] - 1.5 * X_new[:, 1])).astype(int)    # the concept changed
model = LogisticRegression().fit(X_tr, y_tr)
print("KS p-values per feature:", [round(float(ks_2samp(X_tr[:, j], X_new[:, j]).pvalue), 3) for j in range(2)])
print(f"positive rate: training {y_tr.mean():.3f}, new {y_new.mean():.3f}")
print(f"accuracy: training-like data {model.score(X_tr, y_tr):.3f}, new data {model.score(X_new, y_new):.3f}")
KS p-values per feature: [0.424, 0.502]
positive rate: training 0.507, new 0.503
accuracy: training-like data 0.818, new data 0.583

The inputs pass every test (KS p-values 0.424 and 0.502), even the share of positives is the same (0.507 vs 0.503), but accuracy falls from 0.818 to 0.583, close to guessing. Nothing in the inputs warned of it. Concept shift is caught only by collecting labels after deployment (delayed outcomes, a sample sent for human review) and tracking the model's real metrics over time, and fixed by retraining on recent data. Watching the distribution of the model's own scores can give an early hint for some concept shifts, but not this one, since the inputs and therefore the scores look the same.

What to do in practice

  1. Before deployment: evaluate on data from the target setting (External Validation), and on time-ordered splits if the world changes over time (Time-Series Backtesting).
  2. Detect: compare input distributions (KS or population-stability tests per feature, a domain classifier for the joint distribution) and the distribution of the model's scores. Track label-based metrics as soon as labels arrive.
  3. Correct: importance weighting for covariate shift (when the weights are not extreme), prior correction for label shift, retraining on recent data for concept shift.
  4. Design for it: features that are stable across settings, models whose behaviour outside the training range is safe (Robustness Testing), a fallback when inputs look unfamiliar.

Practice

  1. A domain classifier separates last year's training data from this month's data with AUC 0.51. Is the model safe?
Answer

The inputs have not shifted detectably, so covariate shift is unlikely. Label or concept shift can still have happened; only labelled recent data can rule out concept shift.

  1. Why can importance weighting fail when the training and deployment distributions barely overlap?
Answer

The weights pprod/ptrainp_{\text{prod}}/p_{\text{train}} become huge for the few training rows in the deployment region, so the effective sample size collapses and the weighted fit is very noisy. Where training data has no support at all, no reweighting can help: you need data from there.

  1. A classifier trained with 50 % positives gives p=0.6p = 0.6 for a case. Deployment prevalence is 10 %. What is the corrected probability?
Answer

0.6⋅0.20.6⋅0.2+0.4⋅1.8=0.120.12+0.72≈0.143\frac{0.6 \cdot 0.2}{0.6 \cdot 0.2 + 0.4 \cdot 1.8} = \frac{0.12}{0.12 + 0.72} \approx 0.143, using π′/π=0.1/0.5=0.2\pi'/\pi = 0.1/0.5 = 0.2 and (1−π′)/(1−π)=0.9/0.5=1.8(1 - \pi')/(1 - \pi) = 0.9/0.5 = 1.8.

Test yourself

Under covariate shift, what changes and what stays?

  1. P(y)P(y) changes, P(x∣y)P(\mathbf{x} \mid y) stays
  2. P(x)P(\mathbf{x}) changes, P(y∣x)P(y \mid \mathbf{x}) stays
  3. P(y∣x)P(y \mid \mathbf{x}) changes, P(x)P(\mathbf{x}) stays
  4. Nothing changes

A domain classifier distinguishes training rows from deployment rows with AUC 0.90. What does that mean?

  1. The model is 90 % accurate
  2. The input distributions differ substantially
  3. There is concept shift
  4. The labels have changed

Which kind of shift cannot be detected from the inputs alone?

  1. Covariate shift
  2. Concept shift
  3. A change in one feature's mean
  4. A new category appearing

For label shift, what does the prior correction change?

  1. The model's weights
  2. The predicted probabilities, rescaled by the ratio of new to old class priors
  3. The features
  4. Nothing, label shift needs no correction