Search

Search papers and lessons

Covariate Shift

Level 3 · 11 min read

Covariate shift is when the inputs a model sees change between training and use, while the rule that maps inputs to labels stays the same. Reweighting the training examples by a density ratio corrects for it.

On this page

  • Colour = topic mix
  • Probability
  • Calculus
  • Sampling
  • Learning basics
  • Discrete math
  • Sign in to see your progress

TL;DR

A model learns from examples gathered in one setting and is then used in another. Covariate shift is the case where the inputs change between those settings (the mix of ages, images, sentences or sensor readings), but the correct answer for a given input stays the same. The model's mistakes then land on a different part of the input space from the one it was tuned for. If you know how much more or less likely each input is in the new setting, you can reweight the training examples so that the training loss behaves like the loss on the new setting.

Where you'll see it: a medical model trained on patients from one hospital and deployed in another, a spam filter facing an inbox whose mix of messages has drifted, and off-policy evaluation, where the logged data came from an older decision policy.

Intuition

Same rule, different crowd

Suppose a bank trained a loan model on applications from 2019, when most applicants had salaried jobs. Now most applicants are freelancers. For any particular applicant, the chance of default given their income, credit history and job (a conditional probability) is what it always was. The economy has not changed how a person's finances map to risk. What changed is the crowd that walks in. That is covariate shift. The inputs have a new distribution, but the conditional probability of the label given the input, p(y∣x)p(y \mid x), stays put.

The word comes from regression. The inputs of a regression are called covariates, so a shift in the covariates is a shift in the inputs.

Why does this hurt? A model is a compromise. It spends its capacity fitting the regions of input space where training examples are dense, because that is where its loss is measured. In regions it rarely saw, it guesses. If the new crowd lives mostly in those regions, the guesses are what the user experiences. The rule is fine. The model was graded on the wrong crowd.

The fix is intuitive too. If freelancers are rare in the 2019 data but common now, each freelancer in the training set should count for more. Give each example a weight equal to how common its kind of input is in the new world divided by how common it was in the old. The weighted training loss then looks like a loss measured on the new world.

−4−3−2−10123400.10.20.30.40.5xdensity
  • training inputs, N(0, 1)
  • deployment inputs, N(1, 1)
The input distribution moves one unit to the right. If the labelling rule is unchanged, the model should be judged on the dashed curve, not the solid one.

What does not change

The whole idea depends on p(y∣x)p(y \mid x) being the same in both settings. If the rule itself changes, the problem is different. A fraud pattern that adapts to your filter is concept drift, and reweighting the inputs does not repair it. A change in how often each label appears, with the inputs for each label unchanged, is label shift, which needs a different correction. Before reaching for covariate-shift methods, check that the labelling rule really is stable.

The math

Setup

Training pairs (xi,yi)(x_i, y_i) are drawn from ptrain(x) p(y∣x)p_{\text{train}}(x)\, p(y \mid x). At deployment, inputs come from ptest(x)p_{\text{test}}(x) and labels still come from p(y∣x)p(y \mid x). Let fθf_\theta be the model and ℓ(fθ(x),y)\ell(f_\theta(x), y) the loss on one example, for instance squared error. What we want to minimise is the expected loss on the deployment inputs:

Rtest(θ)=Ex∼ptest[ Ey∼p(y∣x)[ℓ(fθ(x),y)]].R_{\text{test}}(\theta) = \mathbb{E}_{x \sim p_{\text{test}}}\Big[\, \mathbb{E}_{y \sim p(y \mid x)}\big[\ell(f_\theta(x), y)\big] \Big].

The plain training loss averages over ptrainp_{\text{train}} instead, so it estimates a different number.

Definition: Covariate shift

A change of data distribution in which the input distribution differs between training and test, ptrain(x)≠ptest(x)p_{\text{train}}(x) \neq p_{\text{test}}(x), while the conditional distribution of the label does not, ptrain(y∣x)=ptest(y∣x)p_{\text{train}}(y \mid x) = p_{\text{test}}(y \mid x) for every input xx that has positive density in both.

The importance weight

Define the importance weight (also called the density ratio)

w(x)=ptest(x)ptrain(x).w(x) = \frac{p_{\text{test}}(x)}{p_{\text{train}}(x)}.

Write L(θ,x)=Ey∼p(y∣x)[ℓ(fθ(x),y)]L(\theta, x) = \mathbb{E}_{y \sim p(y \mid x)}[\ell(f_\theta(x), y)] for the average loss at one input. Then

Rtest(θ)=∫ptest(x) L(θ,x) dx=∫ptrain(x) w(x) L(θ,x) dx=Ex∼ptrain[w(x) L(θ,x)].R_{\text{test}}(\theta) = \int p_{\text{test}}(x)\, L(\theta, x)\, dx = \int p_{\text{train}}(x)\, w(x)\, L(\theta, x)\, dx = \mathbb{E}_{x \sim p_{\text{train}}}\big[w(x)\, L(\theta, x)\big].

This is the importance sampling identity. Step by step:

  1. Write the expectation over test inputs as an integral against ptestp_{\text{test}}.
  2. Replace ptest(x)p_{\text{test}}(x) by w(x) ptrain(x)w(x)\, p_{\text{train}}(x). This is an identity wherever ptrain(x)>0p_{\text{train}}(x) \gt 0.
  3. Read the last integral as an expectation over training inputs.

The sample version is a weighted average of training losses:

R^(θ)=1n∑i=1nw(xi) ℓ(fθ(xi),yi).\hat{R}(\theta) = \frac{1}{n} \sum_{i=1}^{n} w(x_i)\, \ell(f_\theta(x_i), y_i).

Training with this objective is weighted empirical risk minimisation. For a probabilistic model it is weighted maximum likelihood: maximise ∑iw(xi)log⁡pθ(yi∣xi)\sum_i w(x_i) \log p_\theta(y_i \mid x_i).

There is one condition. The weights exist only where the training data has support, so you need ptrain(x)>0p_{\text{train}}(x) \gt 0 wherever ptest(x)>0p_{\text{test}}(x) \gt 0. If the deployment crowd lives in a region the training set never visits, no weighting can recover what the model should do there.

Estimating the weight

When the densities are known, as in a simulation where you chose both distributions, you can compute ww directly. With real data you usually need to estimate it. A standard trick is a domain classifier. Pool an equal number of training and deployment inputs, label them 0 and 1, and train a classifier. Let q(x)q(x) be its output, the probability that an input came from the deployment set. By Bayes' rule, with equal sample sizes,

q(x)1−q(x)=ptest(x)ptrain(x)=w(x).\frac{q(x)}{1 - q(x)} = \frac{p_{\text{test}}(x)}{p_{\text{train}}(x)} = w(x).

So the odds of the classifier are the weight.

Worked examples

Example
Tiny case by hand: train N(0, 1), test N(1, 1)

First, the weight. Both densities share the constant 1/2π1/\sqrt{2\pi}, which cancels:

w(x)=exp⁡ ⁣(−(x−1)2/2)exp⁡ ⁣(−x2/2)=exp⁡ ⁣(x−12).w(x) = \frac{\exp\!\big(-(x-1)^2/2\big)}{\exp\!\big(-x^2/2\big)} = \exp\!\Big(x - \tfrac{1}{2}\Big).

The step uses (x−1)2=x2−2x+1(x-1)^2 = x^2 - 2x + 1, so the exponent is −12(x2−2x+1)+12x2=x−12-\tfrac12(x^2 - 2x + 1) + \tfrac12 x^2 = x - \tfrac12.

Three training examples, with losses:

xxlossw(x)w(x)
−1-10.8e−1.5=0.2231e^{-1.5} = 0.2231
0.50.50.2e0=1.0000e^{0} = 1.0000
221.0e1.5=4.4817e^{1.5} = 4.4817
  1. The naive average loss is (0.8+0.2+1.0)/3=0.667(0.8 + 0.2 + 1.0)/3 = 0.667.
  2. The weighted terms are 0.2231×0.8=0.17850.2231 \times 0.8 = 0.1785, 1.0×0.2=0.20001.0 \times 0.2 = 0.2000 and 4.4817×1.0=4.48174.4817 \times 1.0 = 4.4817.
  3. Their sum is 4.86024.8602. Dividing by n=3n = 3 gives R^=1.620\hat{R} = 1.620.

The deployment population sits further right, near x=2x = 2, where the loss is high. The example at x=2x = 2 is one point in the training data, but it carries most of the weight, so the corrected estimate of 1.62 is far above the naive 0.67. The naive number would have told you the model is doing fine on the crowd it was trained on.

−2−1012340123456xweight
  • w(x) = p_test(x) / p_train(x)
The weight grows exponentially with x. Examples on the right side of the training data, where the deployment inputs live, count far more than examples on the left.
Example
Realistic case: weights from a domain classifier

Suppose a review-sentiment model was trained on 2015 reviews and will be used on 2024 reviews. A domain classifier, trained on equal numbers of each year, gives three reviews these outputs:

  1. Review A: q=0.2q = 0.2, so w=0.2/0.8=0.25w = 0.2 / 0.8 = 0.25. The classifier thinks it looks like 2015 text, so it counts for a quarter of an example.
  2. Review B: q=0.5q = 0.5, so w=1w = 1. The classifier cannot tell the years apart here, so the review counts as usual.
  3. Review C: q=0.9q = 0.9, so w=0.9/0.1=9w = 0.9 / 0.1 = 9. It looks like 2024 text, so it counts nine times.

Weighting by these numbers makes the training loss look more like the 2024 loss. The cost shows up in the effective sample size,

neff=(∑iwi)2∑iwi2.n_{\text{eff}} = \frac{\left(\sum_i w_i\right)^2}{\sum_i w_i^2}.

For the three weights of the tiny case, ∑wi=5.705\sum w_i = 5.705 and ∑wi2=21.135\sum w_i^2 = 21.135, so neff=32.54/21.14≈1.5n_{\text{eff}} = 32.54 / 21.14 \approx 1.5. Three examples carry the information of about 1.5 equal examples, because one weight dominates. Big weights buy bias reduction at the price of variance.

Tradeoffs and failure modes

Covariate-shift correction is the right tool when the labelling rule is stable and the shift is in the inputs. Its main failure mode is extreme weights. The table lists the common situations.

SituationWhat goes wrongBetter choice
Ratio is moderate and p(y∣x)p(y \mid x) is stableReweighting works as describedImportance-weighted training
A few weights are hugeVariance explodes and neffn_{\text{eff}} collapses onto a handful of examplesClip the weights, regularise, or collect target data
High-dimensional inputs such as images or textDensity ratios are hard to estimate directlyDomain classifier, or estimate the ratio in a learned feature space
No overlap: ptrain(x)=0p_{\text{train}}(x) = 0 where ptest(x)>0p_{\text{test}}(x) \gt 0No weight can fix a region the model never sawCollect data in the new region, then fine-tune
The labelling rule itself changesWeights correct the wrong thingConcept-drift methods, monitoring, retraining
Label frequencies change but inputs given the label do notThis is label shift, not covariate shiftPrior correction

Two practical points. First, the domain classifier is a test as well as an estimator. If it cannot beat 50% accuracy at telling the two sets apart, the shift is small and the weights are close to 1, so reweighting changes little. Second, keep the domain classifier separate from the model you are training.

When the shift is large, reweighting is often the wrong first move. Fine-tuning on a modest amount of labelled deployment data (Fine-Tuning) or adapting features with Transfer Learning usually works better, because they change what the model learns rather than only how much each example counts.

A common mistake is to call any change in the data covariate shift. Test for it before correcting for it. A shift in the inputs that leaves p(y∣x)p(y \mid x) intact is rare in the wild, and many "shift" problems turn out to be label shift or concept drift.

History

Covariate shift has an older and a newer history. The weighting idea is much older. Importance sampling was used in the late 1940s and early 1950s, when physicists such as Herman Kahn used reweighted random samples to estimate how particles pass through shielding. The trick is the same as in the derivation above: sample from an easy distribution and correct with a ratio.

The statistical picture arrived in 2000. Hidetoshi Shimodaira showed that under covariate shift, predictive inference is improved by weighting the log-likelihood with the density ratio, and his paper gave the term its standard meaning. In the late 2000s, density-ratio estimation became its own research area, and a 2009 book by Quiñonero-Candela, Sugiyama, Schwaighofer and Lawrence collected the work on dataset shift in machine learning.

Deep learning brought a different use of the phrase. In 2015, Ioffe and Szegedy called the drift of layer inputs during training "internal covariate shift" and proposed batch normalization to reduce it. In 2018, Santurkar and colleagues showed that batch normalization helps for other reasons, which left the term's meaning in that setting disputed. The usage is loose, and it is not the same as the precise covariate shift defined here.

Check yourself

QuestionWhat quantity stays the same under covariate shift, and what changes?Show answer

The conditional distribution p(y∣x)p(y \mid x) stays the same. The marginal distribution of the inputs, p(x)p(x), changes from ptrainp_{\text{train}} to ptestp_{\text{test}}. The model's rule for a given input is still right; it is the mix of inputs that moved.

QuestionTraining inputs are N(0,1)\mathcal{N}(0, 1) and deployment inputs are N(2,1)\mathcal{N}(2, 1). What is the importance weight at a training example x=3x = 3?Show answer

w(x)=exp⁡(2x−2)w(x) = \exp(2x - 2). Here exp⁡(2×3−2)=exp⁡(4)≈54.6\exp(2 \times 3 - 2) = \exp(4) \approx 54.6. A training example that far to the right stands in for about 55 typical examples of the deployment population, so one such example dominates the weighted loss.

QuestionWhy does an unweighted training loss estimate the wrong quantity under covariate shift, even when the model is flexible enough to fit the labels perfectly?Show answer

The unweighted loss averages over ptrain(x)p_{\text{train}}(x), but the target is an average over ptest(x)p_{\text{test}}(x). A flexible model can fit the training data well everywhere it has examples and still be inaccurate where the deployment inputs concentrate, because the training loss gives those regions little weight. Fitting better does not change which regions are measured.

QuestionA colleague proposes importance weights of about 10410^4 for some training points. What is the problem, and what would you check before using them?Show answer

Such a weight means one example would dominate the weighted loss, and the effective sample size would collapse toward one or a few points. The estimate would have huge variance, and the model would overfit those points. Check the effective sample size, look at whether the ratio is estimated from a domain classifier that is overconfident, and consider clipping the weights or collecting more data in the region where the ratio is extreme.

Sources