Covariate, Label & Concept Shift
Detecting and correcting distribution shift.
Every guarantee in this course so far assumed that test data come from the training distribution. Drop that assumption and almost nothing survives, unless something links the two distributions. This lesson works out what can still be proved: what importance weighting costs, how to estimate density ratios and new class priors without a single target label, how to detect a shift, and why predictors meant to survive unseen shifts have so far mostly failed to beat plain empirical risk minimization.
What you’ll learn
- State the importance-weighting identity with its overlap condition, compute the second moment of the weights as a Rényi divergence, and explain when reweighting is needed at all.
- Derive density-ratio estimators from a domain classifier, kernel mean matching and KLIEP, and compare their assumptions.
- Prove the confusion-matrix identity behind black-box shift estimation, state its error bound, and derive the EM update for new class priors.
- Build shift detectors from two-sample tests, separate concept drift from covariate and label shift, and assess invariant risk minimization and its critiques.
What must stay fixed, and what weighting costs
Under distribution shift, labeled examples come from a source and the model is judged on a target . Without some link between the two, source data say nothing about target risk: for any , a target distribution with the same input marginal but flipped labels makes as bad as you like. Every positive result below rests on an assumption that some piece of the joint distribution is shared, together with overlap: must not put mass where has none.
Take a one-dimensional mean shift: source , target . The importance weight is an exponential tilt:
Square it and integrate against the source. Completing the square leaves a Gaussian density times a constant:
Since , the effective sample size converges to as grows, by the law of large numbers. In dimensions with independent coordinates the factors multiply, : the cost is exponential in the squared shift, which is why reweighting rarely survives large shifts in high dimension.
A change of scale can be worse. With source and target , the integrand decays only if . A source narrower than gives weights with infinite second moment: a few tail points eventually dominate any sample.
You have labeled source examples from and the target is . Using exact importance weights, roughly how many examples' worth of information does the weighted estimate carry?
Show the answer
183 examples
, so . The target's typical points, around , sit two standard deviations into the source's tail, where only a few percent of the training data live, and those few receive weights that run into the hundreds. The sample's own diagnostic usually reads higher at this (a median near 330 in simulation): half of comes from , where a sample of 10,000 expects fewer than one point. With heavy-tailed weights the diagnostic flatters.
Bounded second moments are enough for learning guarantees, even when the weights themselves are unbounded. Cortes, Mansour & Mohri (2010) proved that for a class of finite pseudo-dimension, whenever , the target risk exceeds the weighted empirical risk, with high probability and uniformly over the class, by at most a term of order (up to logarithms): slower than the unweighted . For bounded weights they also proved a lower bound showing that the dependence on cannot be avoided.
Is weighting needed at all? Shimodaira (2000) separated two cases for parametric models fitted by maximum likelihood. If the model is well specified, the unweighted estimator stays consistent under covariate shift, because every input region identifies the same true parameter; the weighted estimator is consistent too, but it is not efficient and can be unstable, so reweighting only costs variance. If the model is misspecified, the unweighted estimator converges to the parameter that best fits the source inputs, while the weighted one converges to the best fit for the target, at the price of instability. Shimodaira also corrected AIC to stay asymptotically unbiased under covariate shift, for model selection. Sugiyama, Krauledat & Müller (2007) tuned compromises such as flattened weights , , by importance-weighted cross-validation, which stays almost unbiased under covariate shift for any loss, model and learning method.
Estimating density ratios
Estimating and separately and dividing compounds two hard problems: density estimation degrades quickly with dimension, and small errors in a denominator near zero explode. The methods that work estimate the ratio directly, from source inputs and target inputs .
| Method | Estimate | Strengths and limits |
|---|---|---|
| Probabilistic classification | Fit by logistic loss; then . The logit of a well-specified logistic model is . | any classifier and any feature representation; calibration of matters, and errors near blow up |
| Kernel mean matching (Huang et al., 2007) | Choose weights so the weighted source mean embedding matches the target one: subject to and | a quadratic program in the Gram matrix; weights only at source points (no out-of-sample ); kernel width and chosen by hand |
| KLIEP (Sugiyama et al., 2008) | Model with and centers at target points; maximize subject to | minimizes ; a convex program; kernel width by likelihood cross-validation |
KLIEP maximizes subject to . What does the constraint do?
- It makes a probability density over the target inputs
- It makes integrate to one (in sample), so it is a valid model of and the KL objective is well posed
- It forces the weights to be bounded
- It removes the need for overlap between source and target
Show the answer
B. It makes integrate to one (in sample), so it is a valid model of and the KL objective is well posed
, so minimizing it means maximizing , but only among for which is a density: , estimated by the source average. Without it, scaling up would increase the objective forever.
Whatever the estimator, two diagnostics belong in every report: the effective sample size of the fitted weights, and the domain classifier's AUC. An AUC near 1 means the samples are nearly separable, the true weights are nearly degenerate, and the honest conclusion is that the source data cannot support claims about the target. Weight clipping and flattening () trade bias for variance; estimating ratios in a learned low-dimensional representation trades a different bias (the representation may discard what matters) for feasibility. The book of Sugiyama, Suzuki & Kanamori (2012) develops these estimators and their convergence rates.
Label shift: priors from predictions
Assume label shift, for every class, and that every class that occurs in the target occurs in the source. The unknown is the weight vector , to be estimated from labeled source data and unlabeled target inputs. The trick is to compress through any fixed classifier first.
Fix a classifier (trained on separate source data) and write . The prediction depends on only through , so label shift passes to the predictions:
Sum over the true label, and multiply and divide by . The result is a linear system whose matrix is the source's joint confusion matrix:
is estimable from a labeled source holdout and from the target predictions alone. If is invertible, black-box shift estimation (BBSE) solves with plug-in estimates (Lipton, Wang & Smola, 2018):
The older alternative is maximum likelihood. Under label shift the target density is a mixture with known components, , so the log-likelihood of the new priors on unlabeled inputs is
a concave function of (a log of a linear function). EM maximizes it by alternating a posterior correction with an average (Saerens, Latinne & Decaestecker, 2002):
Unlike BBSE, this needs calibrated source probabilities. Alexandari, Kundaje & Shrikumar (2020) found that after a suitable recalibration on source data (temperature scaling plus class-specific bias terms), maximum likelihood outperformed retraining with BBSE weights and with the regularized RLLS weights of Azizzadenesheli et al. (2019) across their benchmarks.
Your image classifier is accurate but badly overconfident, and you have no labeled data to recalibrate it in the target domain (you do have a labeled source holdout). You want the new class priors. Which statement is right?
- EM is the safe choice, because maximum likelihood never needs calibration
- Neither works: label-shift estimation requires target labels
- BBSE works as long as the source confusion matrix is invertible; EM should first be recalibrated on the source holdout
- BBSE fails, because an overconfident classifier makes the confusion matrix singular
Show the answer
C. BBSE works as long as the source confusion matrix is invertible; EM should first be recalibrated on the source holdout
BBSE uses only the hard predictions' joint distribution with the labels, so miscalibration is irrelevant; it needs invertible, which an accurate classifier easily gives. EM's likelihood treats as the true posterior, so overconfidence biases the estimated priors unless you recalibrate first, and recalibration needs only source labels.
Detecting shift, and concept drift
Detection is a two-sample problem: given a reference sample and a recent one, test . With high-dimensional inputs, power depends on what you test. Rabanser, Günnemann & Lipton (2019) compared pipelines of a dimensionality reduction followed by a test, on image data with simulated shifts of many kinds and sizes. Their main findings:
- The best reduction for univariate tests, and the best overall, was the trained classifier's own softmax outputs (black-box shift detection), followed by a Kolmogorov–Smirnov test per output with a Bonferroni correction.
- Despite the conservative correction, aggregated univariate tests performed comparably to multivariate kernel tests (MMD) on learned representations.
- Domain classifiers did poorly with 100 or fewer target samples but caught up with more, and they help characterize a shift: which examples typify it and whether it hurts accuracy.
import numpy as np
from scipy.stats import ks_2samp
def bbsd_test(model, X_ref, X_new, alpha=0.05):
"""Black-box shift detection: one KS test per softmax output, Bonferroni-corrected."""
P_ref = model.predict_proba(X_ref) # n_ref x k
P_new = model.predict_proba(X_new) # n_new x k
k = P_ref.shape[1]
pvals = np.array([ks_2samp(P_ref[:, j], P_new[:, j]).pvalue for j in range(k)])
return pvals.min() < alpha / k, pvals # True: reject "no shift"Testing in the model's output space is cheap and targets what matters for the model, but it is blind to input changes the model ignores. That is often a feature: a shift the model cannot see in its outputs is less likely to change its decisions.
Concept drift is the change no input test can see. If but , the two input samples have identical distributions, so every test on inputs has power equal to its level. Detection needs labels, and with labels arriving as a stream it becomes change detection on the error sequence. The survey of Gama et al. (2014) distinguishes sudden, incremental, gradual (alternating between old and new concepts) and recurring drift, and adaptation strategies that range from fixed windows to explicit detectors. ADWIN (Bifet & Gavaldà, 2007), for example, keeps a window of recent errors whose length is recomputed online, dropping the older part whenever two sub-windows have significantly different means, with bounds on the rates of false positives and false negatives. Sequential detectors with optimality guarantees, such as CUSUM, are derived in ML Systems: Technical Debt & Monitoring.
Think first A drift detector on inputs fires, but on a small freshly labeled sample the model's accuracy is unchanged. False alarm?
Not necessarily, and not necessarily harmless either. The shift may be real but benign: mass moved into regions where the model was already accurate, or along directions the model ignores. It may also be malignant but rare so far, invisible in a small labeled sample. Look at where the mass moved, using the domain classifier's most "target-like" examples, check accuracy and calibration there specifically, and remember that the weighted training error with estimated predicts the target error only to the extent the effective sample size allows.
Hoping for invariance: domain generalization
Reweighting needs target inputs. Domain generalization asks for more: train on several environments and perform well on environments never seen, with no target data at all. The WILDS benchmark (Koh et al., 2021) collected ten datasets with shifts that arise in practice: across hospitals for tumor identification, across camera traps for wildlife, across time and place in satellite imagery. On every one, standard training lost substantially between in-distribution and out-of-distribution evaluation, and methods designed for shift did not close the gaps.
Invariant risk minimization (IRM; Arjovsky, Bottou, Gulrajani & Lopez-Paz, 2019) looks for a representation on which a single classifier is optimal in every training environment, hoping that only causal, stable features have that property. Its practical version, IRMv1, freezes a scalar classifier and penalizes the gradient of each environment's risk with respect to it:
The empirical verdict was as sobering. Gulrajani & Lopez-Paz (2021) built DomainBed, a testbed of seven multi-domain datasets, nine algorithms and three model-selection rules, and found that empirical risk minimization, carefully implemented and tuned, performed at the state of the art across all datasets. Their methodological point outlived the numbers: a domain-generalization algorithm without a model-selection rule that uses no target data is incomplete, because choosing hyperparameters on the test domain smuggles in exactly the information the method claims not to need.
Key takeaways
- Without a shared component of the joint distribution and overlap, source data say nothing about target risk. With them, , and the variance is governed by : for a Gaussian mean shift, infinite for a source narrower than .
- Reweighting is needed for misspecified models; for correctly specified ones the unweighted MLE is consistent and efficient (Shimodaira). Learning bounds survive unbounded weights with finite second moment, at a slower rate (Cortes, Mansour & Mohri).
- Density ratios come from domain classifiers, kernel mean matching or KLIEP; the effective sample size and the domain AUC say whether the source can support claims about the target at all.
- Label shift is identified through any classifier with an invertible confusion matrix: (BBSE, squared error ), or by EM on calibrated posteriors.
- Shift detection works best in the model's output space; concept drift with unchanged is invisible without labels. Invariance-based domain generalization has strong assumptions and weak empirical gains over well-tuned ERM.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Source , target , exact importance weights. Roughly what fraction of the nominal sample size does the weighted estimate effectively use?
- About 61%
- About 37%
- About 50%
- About 14%
Show the answer
B. About 37%
, so . A shift of one standard deviation already discards nearly two-thirds of the information; two standard deviations keep under 2%.
Under covariate shift, you fit a correctly specified parametric model by maximum likelihood. What does Shimodaira's analysis say about importance weighting?
- It is required: without it the estimator is inconsistent
- It is unnecessary for consistency, and since the unweighted estimator is efficient, weighting can only increase variance
- It removes the need for overlap
- It makes the estimator unbiased in finite samples, at no cost
Show the answer
B. It is unnecessary for consistency, and since the unweighted estimator is efficient, weighting can only increase variance
With a correct model, every region of input space identifies the same true parameter, so the unweighted fit is consistent and asymptotically efficient. Weighting matters under misspecification, where the unweighted fit targets the best approximation for the source inputs rather than the target ones.
A three-class source classifier always predicts class 1 or class 2, never class 3. What happens to black-box shift estimation?
- Nothing: BBSE works with any classifier
- It overestimates but remains consistent
- It needs calibrated probabilities instead
- The confusion matrix has a zero row, so it is singular and is not identified from the predictions
Show the answer
D. The confusion matrix has a zero row, so it is singular and is not identified from the predictions
for every , so is singular and has infinitely many solutions. A predictor that never outputs a class carries no information about how common that class has become.
In the linear model of Rosenfeld, Ravikumar & Risteski, data have environmental features. With how many training environments does the exact IRM solution recover the optimal invariant predictor?
- 2 or more
- 5 or more
- 11 or more
- It never does
Show the answer
C. 11 or more
Their threshold is : with 11 or more environments the solution is the optimal invariant predictor; with 10 or fewer it uses non-invariant features. High-dimensional data typically have far more environmental directions than available environments.
Further reading
- H. Shimodaira, "Improving predictive inference under covariate shift by weighting the log-likelihood function," Journal of Statistical Planning and Inference 90(2), 227–244 (2000).
- C. Cortes, Y. Mansour & M. Mohri, "Learning bounds for importance weighting," Advances in Neural Information Processing Systems 23 (2010).
- M. Sugiyama, T. Suzuki & T. Kanamori, Density Ratio Estimation in Machine Learning (Cambridge University Press, 2012).
- Z. C. Lipton, Y.-X. Wang & A. Smola, "Detecting and correcting for label shift with black box predictors," ICML (2018).
- S. Rabanser, S. Günnemann & Z. C. Lipton, "Failing loudly: an empirical study of methods for detecting dataset shift," NeurIPS (2019).
- I. Gulrajani & D. Lopez-Paz, "In search of lost domain generalization," ICLR (2021).