Simple Algorithm
Machine Learning · Convergence · 28 min

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 PsP_s and the model is judged on a target PtP_t. Without some link between the two, source data say nothing about target risk: for any hh, a target distribution with the same input marginal but flipped labels makes Rt(h)R_t(h) 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: PtP_t must not put mass where PsP_s has none.

DerivationHow fast the second moment grows
  1. w(x)=e−(x−μ)2/2e−x2/2=eμx−μ2/2w(x)=\frac{e^{-(x-\mu)^2/2}}{e^{-x^2/2}}=e^{\mu x-\mu^2/2}

    Take a one-dimensional mean shift: source N(0,1)\mathcal N(0,1), target N(μ,1)\mathcal N(\mu,1). The importance weight is an exponential tilt:

  2. Es[w2]=∫e2μx−μ2 e−x2/22π dx=eμ2∫e−(x−2μ)2/22π dx=eμ2\E_s[w^2]=\int\frac{e^{2\mu x-\mu^2}\,e^{-x^2/2}}{\sqrt{2\pi}}\,dx=e^{\mu^2}\int\frac{e^{-(x-2\mu)^2/2}}{\sqrt{2\pi}}\,dx=e^{\mu^2}

    Square it and integrate against the source. Completing the square leaves a Gaussian density times a constant:

  3. neff≈nEs[w2]=n e−∥μ∥2n_{\text{eff}}\approx\frac{n}{\E_s[w^2]}=n\,e^{-\norm{\boldsymbol\mu}^2}

    Since Es[w]=1\E_s[w]=1, the effective sample size (∑iwi)2/∑iwi2(\sum_iw_i)^2/\sum_iw_i^2 converges to n/Es[w2]n/\E_s[w^2] as nn grows, by the law of large numbers. In dd dimensions with independent coordinates the factors multiply, e∥μ∥2e^{\norm{\boldsymbol\mu}^2}: the cost is exponential in the squared shift, which is why reweighting rarely survives large shifts in high dimension.

  4. Es[w2]<∞  ⟺  σs>σt/2\E_s[w^2]<\infty\iff\sigma_s>\sigma_t/\sqrt2

    A change of scale can be worse. With source N(0,σs2)\mathcal N(0,\sigma_s^2) and target N(0,σt2)\mathcal N(0,\sigma_t^2), the integrand pt2/psp_t^2/p_s decays only if 2σs2>σt22\sigma_s^2>\sigma_t^2. A source narrower than σt/2\sigma_t/\sqrt2 gives weights with infinite second moment: a few tail points eventually dominate any sample.

Predict before you look

You have n=10,000n=10{,}000 labeled source examples from N(0,1)\mathcal N(0,1) and the target is N(2,1)\mathcal N(2,1). Using exact importance weights, roughly how many examples' worth of information does the weighted estimate carry?

Show the answer

183 examples

Es[w2]=eμ2=e4≈54.6\E_s[w^2]=e^{\mu^2}=e^4\approx54.6, so neff≈10,000/54.6≈183n_{\text{eff}}\approx10{,}000/54.6\approx183. The target's typical points, around x=2x=2, sit two standard deviations into the source's tail, where only a few percent of the training data live, and those few receive weights e2x−2e^{2x-2} that run into the hundreds. The sample's own diagnostic (∑iwi)2/∑iwi2(\sum_iw_i)^2/\sum_iw_i^2 usually reads higher at this nn (a median near 330 in simulation): half of Es[w2]\E_s[w^2] comes from x>4x>4, 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 d2(Pt ∥ Ps)<∞d_2(P_t\,\|\,P_s)<\infty, the target risk exceeds the weighted empirical risk, with high probability and uniformly over the class, by at most a term of order d2  n−3/8\sqrt{d_2}\;n^{-3/8} (up to logarithms): slower than the unweighted n−1/2n^{-1/2}. For bounded weights they also proved a lower bound showing that the dependence on d2d_2 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 w(x)λw(\mathbf x)^\lambda, 0≤λ≤10\le\lambda\le1, by importance-weighted cross-validation, which stays almost unbiased under covariate shift for any loss, model and learning method.

Estimating density ratios

Estimating psp_s and ptp_t 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 nsn_s source inputs xi\mathbf x_i and ntn_t target inputs xj′\mathbf x'_j.

MethodEstimateStrengths and limits
Probabilistic classificationFit c(x)≈P(target∣x)c(\mathbf x)\approx P(\text{target}\mid\mathbf x) by logistic loss; then w=nsntc1−cw=\frac{n_s}{n_t}\frac{c}{1-c}. The logit of a well-specified logistic model is log⁡w(x)+log⁡(nt/ns)\log w(\mathbf x)+\log(n_t/n_s).any classifier and any feature representation; calibration of cc matters, and errors near c≈1c\approx1 blow up
Kernel mean matching (Huang et al., 2007)Choose weights so the weighted source mean embedding matches the target one: min⁡β∥1ns∑iβiφ(xi)−1nt∑jφ(xj′)∥2\min_{\boldsymbol\beta}\big\lVert\frac1{n_s}\sum_i\beta_i\varphi(\mathbf x_i)-\frac1{n_t}\sum_j\varphi(\mathbf x'_j)\big\rVert^2 subject to 0≤βi≤B0\le\beta_i\le B and ∣1ns∑iβi−1∣≤ϵ\abs{\frac1{n_s}\sum_i\beta_i-1}\le\epsilona quadratic program in the Gram matrix; weights only at source points (no out-of-sample ww); kernel width and BB chosen by hand
KLIEP (Sugiyama et al., 2008)Model w^(x)=∑lαlk(x,cl)\hat w(\mathbf x)=\sum_l\alpha_lk(\mathbf x,\mathbf c_l) with α≥0\boldsymbol\alpha\ge0 and centers at target points; maximize 1nt∑jlog⁡w^(xj′)\frac1{n_t}\sum_j\log\hat w(\mathbf x'_j) subject to 1ns∑iw^(xi)=1\frac1{n_s}\sum_i\hat w(\mathbf x_i)=1minimizes DKL(pt ∥ w^ps)\KL(p_t\,\|\,\hat wp_s); a convex program; kernel width by likelihood cross-validation
Kernel mean matching rests on the identity Es[w(x)φ(x)]=Et[φ(x)]\E_s[w(\mathbf x)\varphi(\mathbf x)]=\E_t[\varphi(\mathbf x)]: for a characteristic kernel the mean embedding determines the distribution, so matching embeddings pins down the ratio in the population limit. The same embeddings power the MMD two-sample test (lesson Kernel Mean Embeddings & Two-Sample Tests).
Check your understanding

KLIEP maximizes 1nt∑jlog⁡w^(xj′)\frac1{n_t}\sum_j\log\hat w(\mathbf x'_j) subject to 1ns∑iw^(xi)=1\frac1{n_s}\sum_i\hat w(\mathbf x_i)=1. What does the constraint do?

  1. It makes w^\hat w a probability density over the target inputs
  2. It makes w^ ps\hat w\,p_s integrate to one (in sample), so it is a valid model of ptp_t and the KL objective is well posed
  3. It forces the weights to be bounded
  4. It removes the need for overlap between source and target
Show the answer

B. It makes w^ ps\hat w\,p_s integrate to one (in sample), so it is a valid model of ptp_t and the KL objective is well posed

DKL(pt ∥ w^ps)=Et[log⁡(pt/ps)]−Et[log⁡w^]\KL(p_t\,\|\,\hat wp_s)=\E_t[\log(p_t/p_s)]-\E_t[\log\hat w], so minimizing it means maximizing Et[log⁡w^]\E_t[\log\hat w], but only among w^\hat w for which w^ps\hat wp_s is a density: ∫w^ ps=Es[w^]=1\int\hat w\,p_s=\E_s[\hat w]=1, estimated by the source average. Without it, scaling w^\hat w 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 (wλw^\lambda) 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, pt(x∣y)=ps(x∣y)p_t(\mathbf x\mid y)=p_s(\mathbf x\mid y) for every class, and that every class that occurs in the target occurs in the source. The unknown is the weight vector w(y)=πt(y)/πs(y)w(y)=\pi_t(y)/\pi_s(y), to be estimated from labeled source data and unlabeled target inputs. The trick is to compress x\mathbf x through any fixed classifier first.

DerivationThe confusion-matrix identity
  1. pt(y^∣y)=∫1{f(x)=y^} pt(x∣y) dx=∫1{f(x)=y^} ps(x∣y) dx=ps(y^∣y)p_t(\hat y\mid y)=\int\mathbf 1\{f(\mathbf x)=\hat y\}\,p_t(\mathbf x\mid y)\,d\mathbf x=\int\mathbf 1\{f(\mathbf x)=\hat y\}\,p_s(\mathbf x\mid y)\,d\mathbf x=p_s(\hat y\mid y)

    Fix a classifier ff (trained on separate source data) and write y^=f(x)\hat y=f(\mathbf x). The prediction depends on yy only through x\mathbf x, so label shift passes to the predictions:

  2. pt(y^=i)=∑yps(y^=i∣y) πt(y)=∑yps(y^=i, y)⏟Ciy w(y)⟺μt=C wp_t(\hat y=i)=\sum_yp_s(\hat y=i\mid y)\,\pi_t(y)=\sum_y\underbrace{p_s(\hat y=i,\ y)}_{C_{iy}}\,w(y)\qquad\Longleftrightarrow\qquad\boldsymbol\mu_t=C\,\mathbf w

    Sum over the true label, and multiply and divide by πs(y)\pi_s(y). The result is a linear system whose matrix is the source's joint confusion matrix:

  3. w^=C^−1μ^t,π^t(y)=w^(y) π^s(y)\hat{\mathbf w}=\hat C^{-1}\hat{\boldsymbol\mu}_t,\qquad\hat\pi_t(y)=\hat w(y)\,\hat\pi_s(y)

    CC is estimable from a labeled source holdout and μt\boldsymbol\mu_t from the target predictions alone. If CC 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, pt(x)=ps(x)∑yw(y) ps(y∣x)p_t(\mathbf x)=p_s(\mathbf x)\sum_yw(y)\,p_s(y\mid\mathbf x), so the log-likelihood of the new priors on unlabeled inputs x1′,…,xm′\mathbf x'_1,\dots,\mathbf x'_m is

ℓ(πt)=∑j=1mlog⁡∑yπt(y)πs(y) ps(y∣xj′)+const,\ell(\boldsymbol\pi_t)=\sum_{j=1}^m\log\sum_y\frac{\pi_t(y)}{\pi_s(y)}\,p_s(y\mid\mathbf x'_j)+\text{const},

a concave function of πt\boldsymbol\pi_t (a log of a linear function). EM maximizes it by alternating a posterior correction with an average (Saerens, Latinne & Decaestecker, 2002):

p(k)(y∣xj′)∝π(k)(y)πs(y) ps(y∣xj′),π(k+1)(y)=1m∑j=1mp(k)(y∣xj′).p^{(k)}(y\mid\mathbf x'_j)\propto\frac{\pi^{(k)}(y)}{\pi_s(y)}\,p_s(y\mid\mathbf x'_j),\qquad\pi^{(k+1)}(y)=\frac1m\sum_{j=1}^mp^{(k)}(y\mid\mathbf x'_j).

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.

Check your understanding

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?

  1. EM is the safe choice, because maximum likelihood never needs calibration
  2. Neither works: label-shift estimation requires target labels
  3. BBSE works as long as the source confusion matrix is invertible; EM should first be recalibrated on the source holdout
  4. 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 CC invertible, which an accurate classifier easily gives. EM's likelihood treats ps(y∣x)p_s(y\mid\mathbf x) 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 H0: Ps=PtH_0{:}\ P_s=P_t. 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.
python
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 Pt(x)=Ps(x)P_t(\mathbf x)=P_s(\mathbf x) but Pt(y∣x)≠Ps(y∣x)P_t(y\mid\mathbf x)\ne P_s(y\mid\mathbf x), 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 ww 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 e∈Ee\in\mathcal E 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 Φ\Phi 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 w=1w=1 and penalizes the gradient of each environment's risk with respect to it:

min⁡Φ ∑e∈ERe(Φ)+λ ∥∇w ∣ w=1Re(w⋅Φ)∥2.\min_\Phi\ \sum_{e\in\mathcal E}R^e(\Phi)+\lambda\,\Big\lVert\nabla_{w\,\mid\,w=1}R^e(w\cdot\Phi)\Big\rVert^2.

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, Rt(h)=Es[Wℓ]R_t(h)=\E_s[W\ell], and the variance is governed by d2(Pt ∥ Ps)=Es[W2]d_2(P_t\,\|\,P_s)=\E_s[W^2]: e∥μ∥2e^{\norm{\boldsymbol\mu}^2} for a Gaussian mean shift, infinite for a source narrower than σt/2\sigma_t/\sqrt2.
  • 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: μt=Cw\boldsymbol\mu_t=C\mathbf w (BBSE, squared error O(σmin⁡−2(∥w∥2log⁡n/n+klog⁡m/m))\order{\sigma_{\min}^{-2}(\norm{\mathbf w}^2\log n/n+k\log m/m)}), or by EM on calibrated posteriors.
  • Shift detection works best in the model's output space; concept drift with unchanged P(x)P(\mathbf x) 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.

Question 1

Source N(0,1)\mathcal N(0,1), target N(1,1)\mathcal N(1,1), exact importance weights. Roughly what fraction of the nominal sample size does the weighted estimate effectively use?

  1. About 61%
  2. About 37%
  3. About 50%
  4. About 14%
Show the answer

B. About 37%

Es[w2]=eμ2=e\E_s[w^2]=e^{\mu^2}=e, so neff≈n/e≈0.37nn_{\text{eff}}\approx n/e\approx0.37n. A shift of one standard deviation already discards nearly two-thirds of the information; two standard deviations keep under 2%.

Question 2

Under covariate shift, you fit a correctly specified parametric model by maximum likelihood. What does Shimodaira's analysis say about importance weighting?

  1. It is required: without it the estimator is inconsistent
  2. It is unnecessary for consistency, and since the unweighted estimator is efficient, weighting can only increase variance
  3. It removes the need for overlap
  4. 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.

Question 3

A three-class source classifier always predicts class 1 or class 2, never class 3. What happens to black-box shift estimation?

  1. Nothing: BBSE works with any classifier
  2. It overestimates πt(3)\pi_t(3) but remains consistent
  3. It needs calibrated probabilities instead
  4. The confusion matrix has a zero row, so it is singular and w\mathbf w is not identified from the predictions
Show the answer

D. The confusion matrix has a zero row, so it is singular and w\mathbf w is not identified from the predictions

C3y=ps(y^=3,y)=0C_{3y}=p_s(\hat y=3,y)=0 for every yy, so CC is singular and μt=Cw\boldsymbol\mu_t=C\mathbf w has infinitely many solutions. A predictor that never outputs a class carries no information about how common that class has become.

Question 4

In the linear model of Rosenfeld, Ravikumar & Risteski, data have de=10d_e=10 environmental features. With how many training environments does the exact IRM solution recover the optimal invariant predictor?

  1. 2 or more
  2. 5 or more
  3. 11 or more
  4. It never does
Show the answer

C. 11 or more

Their threshold is E>deE>d_e: 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).