Detecting dataset shift: two-sample tests and monitoring
Build a drift detection pipeline using dimension reduction, corrected univariate tests, BBSD, MMD, and classifier tests. Compare power, distinguish benign from harmful shift, estimate accuracy without labels, and monitor sequentially.
After this lesson you can
- Design a shift-detection pipeline choosing representation, test, and multiple-comparison control.
- Implement unbiased MMD with a permutation p-value and a classifier two-sample test.
- Compare KS on PCA, BBSD, MMD, and C2ST power across shift types and magnitudes.
- Distinguish benign from harmful shift and estimate accuracy loss without labels using ATC.
- Configure sequential monitoring to control false alarms over time.
Before you start
When the population changes
Imagine a fraud filter with initial accuracy 90%. One month later it falls to 80%, but labels arrive weeks late. The request counter may remain healthy while the merchant mix, transaction distribution, or relationship between features and fraud changes. A detector can alert on the observable distribution before labels arrive, but cannot infer by itself that accuracy has fallen: two worlds can have the same input distribution and different labels. This is a hypothetical scenario, not a measurement.
A shift-detection pipeline fixes a reference, target window, representation, and test before seeing the result. Monitor inputs, activations, predictions, and, once available, labels and disaggregated losses. Each layer answers a different question: a pixel change may disappear in the model, and a change in may be invisible in . The type of shift determines what can be inferred.
A function showing where mass changes
The figure compares small samples with a Gaussian kernel. Move the target cloud and try very large or very small bandwidths. The empirical witness shows where mean similarity to the reference exceeds mean similarity to the target; it is not a density and its scale depends on the kernel.
Let be a positive-definite, bounded, measurable kernel with reproducing kernel Hilbert space . For distributions , their mean embeddings are and . Maximum mean discrepancy (MMD) is the largest expectation difference over the unit ball of . By the reproducing property and Cauchy-Schwarz,
If embeddings differ, the normalized optimal function is ; if they coincide, the supremum is zero. With a characteristic kernel, such as the Gaussian on , zero MMD implies equality of distributions. The unnormalized witness is . The paper by Gretton and colleagues develops the test and its conditions.
For independent samples of sizes , the U estimator of squared MMD is
Each off-diagonal pair has the corresponding expectation in the norm expansion. The estimator is unbiased but can be negative in a finite sample. Under and exchangeable observations, permuting pooled labels gives the conditional null distribution. With random permutations use : the added one protects validity and prevents a zero p-value. Temporal dependence, adapting the reference to the target, or choosing the kernel using test labels invalidates the simple argument.
Validity and power are different questions. If kernel bandwidth is fixed without inspecting domain labels, or obtained from a permutation-invariant function such as the pooled median, the same bandwidth can be retained in every permutation. If bandwidth is selected to maximize observed separation, it must be selected again within each permutation or learned on an independent set. Otherwise the observed statistic benefits from a search not reproduced under the null. With 99 permutations the smallest possible p-value is 0.01: a 0.001-level decision needs many more permutations.
For , the median pooled-sample distance is a permutation-invariant practical rule, not an optimal choice. In high dimensions distances can concentrate; a huge bandwidth makes the kernel nearly constant, while a tiny bandwidth makes almost all pairs zero. A learned kernel may improve power against a particular alternative, but learn it on independent data or repeat learning within each permutation. Liu and colleagues study deep kernels selected for power.
A characteristic Gaussian kernel does not mean a finite window detects every difference with high probability. If is enormous, kernel values differ very little; if tiny, distinct pairs usually have near-zero values. In both cases the statistic may be difficult to distinguish from its permutation distribution. The figure separates this effect from genuine absence of change: cloud locations are visible, but the test observes a similarity determined by the chosen bandwidth.
Four ways to compare two windows
Dimension reduction is fitted only on reference training data. For PCA, apply KS per coordinate and reject if any p-value is below : Bonferroni controls the probability of at least one false positive without requiring independent components. Sensitivity depends on the projection preserving the difference. An autoencoder can replace PCA, but may also erase exactly the relevant change.
Black-box shift detection (BBSD) compares output distributions of a fixed predictor, for example one KS test per class probability with multiple correction. A variant uses predicted labels and a categorical test. Rabanser and colleagues compare representations and tests across shifts; one representation performing well in their experiments does not make it universally best. BBSD may miss a change ignored by the model, and detecting one does not guarantee a utility loss.
The classifier two-sample test (C2ST) assigns each point a domain label, trains a discriminator, and measures accuracy on independent data. With equally likely domains, the Bayes classifier achieves , where is total variation. A restricted classifier gives a lower bound on that capability, not an exact TV estimate. Significance requires calibrating the statistic on an independent split or permutations including training; Lopez-Paz and Oquab formalize the idea.
The curves come from the next lab with eight-component PCA, KS on ten probabilities, MMD on PCA, and logistic C2ST. There is one training split and 20 window draws per point: variation is large and windows reuse a finite set. In this experiment BBSD is sensitive to noise and MMD detects proportion shift well, but ranking depends on predictor, kernel, and dataset. A detector may appear ineffective because the window is too small; failure to reject does not prove equality.
Benign shift, harmful shift, and ATC
In the figure the label is determined before displacement. Moving parallel to the vertical boundary changes one coordinate without crossing it; perpendicular movement can cross it. Both alter the input distribution, but only the second changes decisions relative to original labels. This is an explicit synthetic mechanism, not a generalization about every parallel shift.
ATC (average thresholded confidence) fixes a threshold on labeled calibration data so the fraction of confidences above approximates reference accuracy. On the target, it estimates accuracy as the fraction of confidences above that threshold without using target labels. Ties and discrete quantiles require an explicit convention. This assumes a sufficiently stable relationship between confidence and error: it is not an identity. Garg and colleagues show both empirical usefulness and the impossibility of identifying accuracy in general without assumptions on the shift. A rotation can preserve confidence while changing the correct label. Retain labeled audits and communicate estimation error.
The impossibility is visible without a complicated network. Fix the same target inputs and predictions and consider two possible label assignments: one agrees with every prediction and the other contradicts them. The unlabeled detector receives exactly the same information in both worlds, but accuracy differs. ATC introduces a learned relationship between confidence and error to choose a useful estimate; test that relationship when labels arrive, especially by segment. The boundary figure shows a specific limitation: perpendicular movement can increase confidence in wrong decisions.
Monitoring without sounding an alarm every day
Sequential monitoring compares repeated windows against a reference. If you run 100 tests at 5%, even if each is well calibrated, the probability of at least one false alarm is not 5%. The union of events gives bound even with dependence; distributing a fixed budget over a finite horizon is conservative. Overlapping windows and a shared reference generate dependence, so an independence formula does not automatically apply.
For an indefinite horizon you can reserve : the telescoping sum of levels is . If each test remains valid at its assigned level, the union bound controls the probability of any false alarm without independence. The tradeoff is that levels become very small. A reference refreshed in response to alarms or selected using the same windows being tested needs its own validity argument: allocating levels does not fix miscalibrated p-values.
A CUSUM summarizes accumulated evidence: , with and an alarm when . Drift prevents accumulation under the reference; is calibrated on complete null trajectories reproducing window dependence and horizon. Without stationarity assumptions and calibration of reference changes, the guarantee can fail. CUSUM changes the delay versus false-alarm tradeoff: report both, not only detection time.
In production, version the model, representation, window, and reference; log volume and missing data. Tools such as Evidently or Alibi Detect can calculate metrics, but do not choose the population, alarm level, or intervention cost for you. After an alert, inspect representative examples, review segments, and wait for labels before attributing harm or deploying another model.
Lab: digits and four detectors
Use load_digits normalized to . Training, calibration, and the window pool are disjoint. The classifier and PCA are fitted once. Each repetition draws two disjoint samples from the pool; the target is transformed to create noise, rotation, or proportion shift. This small dataset and these perturbations do not represent every possible domain.
import numpy as np
from scipy.ndimage import rotate
from scipy.stats import ks_2samp, hypergeom
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
X, y = load_digits(return_X_y=True)
X = X / 16
train, pool = train_test_split(np.arange(len(y)), test_size=.7, stratify=y, random_state=31)
cal, pool = train_test_split(pool, test_size=.8, stratify=y[pool], random_state=32)
pca = PCA(n_components=8, random_state=33).fit(X[train])
clf = LogisticRegression(max_iter=400, C=2).fit(X[train], y[train])
cal_conf = clf.predict_proba(X[cal]).max(axis=1)
cal_acc = np.mean(clf.predict(X[cal]) == y[cal])
threshold = np.quantile(cal_conf, 1-cal_acc)
print('train, cal, pool', len(train), len(cal), len(pool), 'cal_acc', round(cal_acc,4), 'umbral ATC', round(threshold,4))The median squared distance is calculated on the pooled sample without domain labels. The statistic is recalculated for every permutation. In C2ST, training and evaluating on the same examples would make accuracy optimistic. Here domain labels in the evaluation half are permuted conditionally: with balanced groups and a fixed number of positive predictions, positive matches follow a hypergeometric distribution under exchangeability.
def mmd2(K, i, j):
a, b, c = K[np.ix_(i, i)], K[np.ix_(j, j)], K[np.ix_(i, j)]
return (a.sum()-np.trace(a))/(len(i)*(len(i)-1)) + (b.sum()-np.trace(b))/(len(j)*(len(j)-1)) - 2*c.mean()
def mmd_p(X, Y, rng, B=99):
Z = np.vstack((X, Y)); n = len(X)
d = ((Z[:,None]-Z[None,:])**2).sum(axis=2)
sigma2 = np.median(d[np.triu_indices(len(Z),1)])
K = np.exp(-d/(2*max(sigma2,1e-12)))
obs = mmd2(K,np.arange(n),np.arange(n,len(Z)))
vals=[]
for _ in range(B):
order = rng.permutation(len(Z)); vals.append(mmd2(K,order[:n],order[n:]))
return (1+np.sum(np.array(vals)>=obs))/(B+1)
def run(mode, magnitude, n, seed):
rng = np.random.default_rng(seed)
a = rng.choice(pool, n, replace=False); rest = np.setdiff1d(pool, a)
if mode == 'label':
weights = np.where(y[rest] == 0, 1+9*magnitude, 1.)
b = rng.choice(rest, n, replace=False, p=weights/weights.sum())
else:
b = rng.choice(rest, n, replace=False)
A, B = X[a].copy(), X[b].copy()
if mode == 'noise': B = np.clip(B + rng.normal(0,magnitude,B.shape),0,1)
if mode in ('rotation','subpopulation'):
changed = np.ones(n, dtype=bool) if mode == 'rotation' else rng.random(n) < magnitude
angle = 24 if mode == 'subpopulation' else magnitude*30
if np.any(changed):
B[changed] = np.array([rotate(row.reshape(8,8), angle, reshape=False, order=1).ravel() for row in B[changed]])
AP, BP = pca.transform(A), pca.transform(B)
pa, pb = clf.predict_proba(A), clf.predict_proba(B)
pca_reject = min(ks_2samp(AP[:,k], BP[:,k]).pvalue for k in range(8)) < .05/8
bbsd_reject = min(ks_2samp(pa[:,k], pb[:,k]).pvalue for k in range(10)) < .05/10
mmd_reject = mmd_p(AP,BP,rng) <= .05
split=n//2
domain=LogisticRegression(max_iter=200).fit(np.vstack((AP[:split],BP[:split])),np.r_[np.zeros(split),np.ones(split)])
pred=domain.predict(np.vstack((AP[split:],BP[split:])))
positives=int(pred.sum()); hits=int(pred[n-split:].sum())
c2st_reject=hypergeom.sf(hits-1,2*(n-split),positives,n-split) < .05
return np.array([pca_reject,bbsd_reject,mmd_reject,c2st_reject],float), np.mean(clf.predict(B)==y[b]), np.mean(pb.max(axis=1)>threshold)Each run below computes a batch of five windows to keep cells small. Change the initial seed, type, and size, and repeat to estimate power. The figure uses 20 windows per combination of mode, size, and magnitude, with seeds 1000 through 1019; power_data.py reproduces the entire grid with local Python and saves power.json.
results = [run('noise', .35, 64, seed) for seed in range(5)]
print('rechazos KS, BBSD, MMD, C2ST:', np.mean([r[0] for r in results],axis=0))
print('exactitud:', np.mean([r[1] for r in results]), 'ATC:', np.mean([r[2] for r in results]))Local lab: topic shifts
Download text_monitor.py and run it with Python, PyTorch, CUDA, and sentence-transformers. It downloads sentence-transformers/all-MiniLM-L6-v2 once at the revision pinned in code. The corpus is generated from custom nature and sports templates: it is a controlled stream, not a representative collection of production messages. Kernel-fitting and evaluation templates differ.
The script compares a Gaussian kernel on normalized embeddings with another adding a supervised projection learned only on independent templates. The projection knows the shift type and may lose sensitivity to other shifts; keeping original features reduces but does not eliminate that risk. It uses 40 pilot trajectories to fix CUSUM centering and drift, and 199 independent null trajectories to calibrate the maximum over 16 windows. Under the simulated mechanism and exchangeability of the 199 null trajectories and the new trajectory, order 190 controls horizon error at 5% conditional on the pilot. This is no guarantee for a dependent real stream or different topics.
That calibration applies separately to each procedure. If several alarms are active and a joint guarantee is required, include their maximum in calibration or divide the level among them. In code, windows are formed by independent sampling with replacement from a finite template corpus: control applies to that empirical generator, not an arbitrary text sequence.
In one run with the same random sequences for both kernels, the original kernel triggered the window test and CUSUM at window 10. The learned-projection kernel triggered them at windows 6 and 8. This is one template trajectory and does not establish general superiority; the projection was trained specifically to distinguish these two topics. The first gradual change begins at window 5. Thresholds were 0.02657 and 0.06417 for the original kernel, and 0.02636 and 0.06439 for the learned one, respectively. Repeat with other seeds and alternatives before designing an operational alarm.
Exercises
mmd_test(X, Y, sigma, B, seed): return the U estimator of MMD² with a Gaussian kernel and the p-value from B permutations with the plus-one correction. X and Y are matrices with at least two rows; use np.random.default_rng(seed) and count ties as extreme.import numpy as np
def mmd_test(X, Y, sigma, B, seed):
passStep 1 of 3. What is the expectation of a term in the first sum when i differs from j?