Module contents
Lesson 19 of 20Advanced 110 min

Distribution shift: the theory of domain adaptation

Study generalization when training and deployment distributions differ. Distinguish covariate, label and concept shift, derive importance weighting and its variance cost, estimate new label proportions, and use the Ben-David domain adaptation bound to understand what alignment can and cannot guarantee.

After this lesson you can

  • Classify real scenarios as covariate, label or concept shift and identify assumptions that make correction possible.
  • Prove unbiasedness of importance weighting and quantify its variance through effective sample size and Rényi divergence.
  • Implement BBSE and the Saerens et al. EM algorithm to estimate label shift and correct a classifier.
  • Prove the Ben-David et al. adaptation bound and estimate discrepancy using a domain classifier.
  • Explain Zhao et al.’s limitation of representation alignment and identify settings where adaptation is impossible.

Before you start

When benchmark performance fails to transfer

A vulnerability detector trained on thousands of labeled Java functions does well on a random held-out split. When deployed on a customer’s Python repository, its false-positive rate spikes. A fraud model calibrated in autumn degrades over the holidays as purchasing patterns change. It degrades again when fraudulent behavior shifts. A return predictor trained in a low-rate environment ceases to be useful after a change in the interest-rate regime.

All three cases violate the assumption behind the module’s previous guarantees: training and deployment data come from the same distribution. The test-set, VC and Rademacher bounds control population risk under the distribution that generates the sample. Applying the model to another distribution calls for additional assumptions.

This lesson asks what holds when the training or source distribution PSP_S differs from the deployment or target distribution PTP_T and only unlabeled target inputs are available. Guarantees depend on how the distributions differ. Each assumption suggests a distinct correction, with its own cost and failure modes.

Notation: PSP_S and PTP_T are distributions on X×Y\mathcal{X}\times\mathcal{Y} with densities pSp_S and pTp_T, or mass functions in the discrete case. Let RS(h)=ES[ℓ(h(X),Y)]R_S(h) = \E_{S}[\ell(h(X), Y)] and RT(h)=ET[ℓ(h(X),Y)]R_T(h) = \E_T[\ell(h(X), Y)] be risks of hh in the two domains. For 0–1 loss write ϵS(h)\epsilon_S(h) and ϵT(h)\epsilon_T(h). We have nn labeled examples from PSP_S and mm unlabeled inputs from PTP_T.

Three ways a distribution can shift

Factor the joint distribution in two ways, p(x,y)=p(x) p(y∣x)=p(y) p(x∣y)p(x, y) = p(x)\,p(y \given x) = p(y)\,p(x \given y). Each factorization suggests which part can change while the other stays fixed.

Except in degenerate settings, a nontrivial shift cannot satisfy both of the first two definitions.

Proof

The two assumptions give pT(x,y)=pT(x) pS(y∣x)p_T(x, y) = p_T(x)\,p_S(y \given x) and pT(x,y)=pT(y) pS(x∣y)p_T(x, y) = p_T(y)\,p_S(x \given y). Divide each by the corresponding factorization of pS(x,y)=pS(x) pS(y∣x)=pS(y) pS(x∣y)p_S(x, y) = p_S(x)\,p_S(y \given x) = p_S(y)\,p_S(x \given y). The ratio pT(x,y)/pS(x,y)p_T(x, y)/p_S(x, y) equals both pT(x)/pS(x)p_T(x)/p_S(x), independent of yy, and pT(y)/pS(y)p_T(y)/p_S(y), independent of xx. For inputs compatible with every class, all pT(y)/pS(y)p_T(y)/p_S(y) must have the same constant value cc. Since ∑ypT(y)=∑ypS(y)=1\sum_y p_T(y) = \sum_y p_S(y) = 1, we have c=1c = 1. Then pT(y)=pS(y)p_T(y) = p_S(y) and, using pT(x∣y)=pS(x∣y)p_T(x \given y) = p_S(x \given y), we get PT=PSP_T = P_S.

∎

Choose the more plausible assumption before correcting a model. Schölkopf et al. (2012) give a criterion based on causal direction. If XX causes YY, as when a protein’s amino acid sequence determines how it folds, the causal mechanism p(y∣x)p(y \given x) can remain stable as sampled inputs change. Covariate shift is then natural. If YY causes XX, as when a disease produces symptoms or a writer’s intended digit produces an image, the stable mechanism is p(x∣y)p(x \given y). Prevalence p(y)p(y) can vary across hospitals or populations, giving label shift. The structural causal models module formalizes this as mechanism invariance.

InteractiveThree forms of distribution shift
  • source density
  • target: filled y = 1, open y = 0
  • true source boundary
  • hSh_S (linear, source fit)
  • fit weighted by w(x)w(x)
Source error of hSh_S19.4 %
Target error of hSh_S55.9 %
With importance weights12.6 %
With updated priors48.3 %
Best linear fit with target labels12.6 %
Target Bayes error12.4 %
neff/n=1/ES[w2]n_{\text{eff}}/n = 1/\mathbb{E}_S[w^2]0.02
Covariate shift: P(y∣x)P(y \mid x) stays fixed, so w(x)=pT(x)/pS(x)w(x) = p_T(x)/p_S(x) puts more emphasis where target data occur. The prior correction assumes label shift.
Source data follow x∼N(0,I2)x \sim N(\vb{0}, \mat{I}_2) and PS(y=1∣x)=σ(3(x2−0.35(x12−1)))P_S(y = 1 \given x) = \sigmoid(3(x_2 - 0.35(x_1^2 - 1))) with gray parabolic boundary. Classifier hSh_S (blue) deliberately uses misspecified linear logistic regression fitted to the source population. In covariate shift the target is N(mT,0.752I)N(\vb{m}_T, 0.75^2\mat{I}) and P(y∣x)P(y \given x) stays fixed. Drag the target center. In label shift, pT(x,y)=pS(x,y) qy/pyp_T(x, y) = p_S(x, y)\,q_y/p_y with q=PT(y=1)q = P_T(y = 1). In concept shift, P(x)P(x) stays fixed and the parabola rotates. Orange points are target samples, filled for y=1y = 1. Corrections use exact weights w(x)=pT(x)/pS(x)w(x) = p_T(x)/p_S(x) for weighted logistic ERM (magenta) or a logit shift log⁡(r1/r0)\log(r_1/r_0) with ry=qy/pyr_y = q_y/p_y (teal). A grid integrates the errors. Initially the target lies where the parabola rises. hSh_S misclassifies over half the examples and the weighted line aligns with the local boundary, close to Bayes error. Compare the corrections under label shift, then rotate the concept.

First, covariate shift increases error here because hSh_S is misspecified. If the model could represent the parabola, the source Bayes classifier would remain optimal because p(y∣x)p(y \given x) stays fixed. The input shift changes where errors matter, so the linear model has to fit the target region. Second, for target center (2.2,0.8)(2.2, 0.8), readout neff/nn_{\text{eff}}/n gives 0.020.02. The population correction works, but in a finite sample a handful of source points can receive nearly all the weight. The next section quantifies that cost. Third, under concept shift, P(x)P(x) stays fixed while the boundary rotates. The corrections leave the model unchanged. Unlabeled inputs do not reveal this change or how to correct it.

Covariate shift and importance weighting

A change of measure rewrites target risk as an expectation under the source distribution.

The guided proof uses the covariate-shift factorization, support inclusion and linearity of expectation. Without support inclusion the same calculation gives ES[wℓ]=ET[ℓ 1[pS(X)>0]]\E_S[w\ell] = \E_T[\ell\,\ind[p_S(X) > 0]]. It misses the target region absent from the source, even with unlimited source data. Unbiasedness also requires fixed hh. The minimizer h^w\hat h_w depends on the sample, so R^w(h^w)\hat R_w(\hat h_w) is downward biased, as in ordinary empirical risk minimization.

When weighting helps

Shimodaira (2000), who introduced the term covariate shift, analyzed weighted maximum likelihood. With a correctly specified model, unweighted maximum likelihood remains asymptotically optimal under covariate shift: the true parameter maximizes expected likelihood in every region, so weighting adds variance. Under misspecification, unweighted fitting converges to the best approximation in the source region. The asymptotically optimal choice under expected Kullback–Leibler loss is ratio pT/pSp_T/p_S, which targets the best approximation in the target region. For moderate samples Shimodaira proposes choosing weights with a variant of an information criterion because exact ratios can be noisy. The previous widget illustrates this: weights determine which part of a parabola a line fits.

Ordinary cross-validation estimates source risk, so its estimate of target risk is biased under covariate shift. Sugiyama, Krauledat and Müller (2007) prove that cross-validation weighted by ww recovers unbiasedness.

Estimating a density ratio with a classifier

In practice pSp_S and pTp_T are unknown. Instead of fitting both high-dimensional densities, pool the nn source inputs with domain label D=0D = 0 and the mm target inputs with label D=1D = 1. Fit a probabilistic domain classifier. Bayes’ rule under this mixture gives

P(D=1∣x)P(D=0∣x)=m pT(x)n pS(x)⟹w(x)=nm P(D=1∣x)P(D=0∣x)=nm elogit(x).\frac{\Pr(D = 1 \given x)}{\Pr(D = 0 \given x)} = \frac{m\,p_T(x)}{n\,p_S(x)} \quad\Longrightarrow\quad w(x) = \frac{n}{m}\,\frac{\Pr(D = 1 \given x)}{\Pr(D = 0 \given x)} = \frac{n}{m}\,e^{\text{logit}(x)}.

With logistic regression on features ϕ(x)\phi(x), the population formula is exact when log⁡(pT/pS)\log(p_T/p_S) is linear in ϕ\phi. For two Gaussian inputs, ϕ(x)=(1,x,x2)\phi(x) = (1, x, x^2) suffices, since their density ratio is the exponential of a quadratic. The quality of w^\hat w depends on probability calibration as well as classification performance.

The lab implements a regression example. The true function is f(x)=−x+x3f(x) = -x + x^3 with noise N(0,0.32)N(0, 0.3^2), and the fitted model is a line. The source is N(0.5,0.52)N(0.5, 0.5^2) and target is N(0,0.32)N(0, 0.3^2). The ratio estimator uses 150 inputs per domain and a hand-written Newton solver for logistic regression.

[ ]Covariate shift from scratch: domain classification and weighted ERMBrowser
import numpy as np
from scipy.stats import norm

f = lambda x: -x + x**3                      # verdad no lineal; el modelo será una recta (mal especificado)
mS, sS, mT, sT = 0.5, 0.5, 0.0, 0.3          # origen N(0.5, 0.5²), destino N(0, 0.3²)
w_true = lambda x: norm.pdf(x, mT, sT) / norm.pdf(x, mS, sS)
feats = lambda x: np.c_[np.ones_like(x), x, x**2]   # log(p_T/p_S) de dos gaussianas es cuadrático

def logistic_newton(F, d, iters=30, lam=1e-6):
    """Regresión logística por Newton: P(D = 1 | x) = sigmoid(F θ)."""
    th = np.zeros(F.shape[1])
    for _ in range(iters):
        p = 1 / (1 + np.exp(-F @ th))
        g = F.T @ (p - d) + lam * th
        H = (F * (p * (1 - p))[:, None]).T @ F + lam * np.eye(F.shape[1])
        th -= np.linalg.solve(H, g)
    return th

def weighted_ls(x, y, w):
    X = np.c_[np.ones_like(x), x]
    return np.linalg.solve((X * w[:, None]).T @ X, (X * w[:, None]).T @ y)

rng = np.random.default_rng(1)
xt = rng.normal(mT, sT, 20000)
yt = f(xt) + rng.normal(0, 0.3, 20000)       # test de destino, solo para evaluar
n = m = 150
mse = {k: [] for k in ["sin pesos", "w exacto", "w estimado", "w estimado ^ 0.5"]}
neff = []
for rep in range(200):
    xs = rng.normal(mS, sS, n); ys = f(xs) + rng.normal(0, 0.3, n)    # origen etiquetado
    xu = rng.normal(mT, sT, m)                                         # destino sin etiquetas
    th = logistic_newton(np.r_[feats(xs), feats(xu)], np.r_[np.zeros(n), np.ones(m)])
    w_est = (n / m) * np.exp(feats(xs) @ th)                           # (n/m) · P(D=1|x)/P(D=0|x)
    for k, w in [("sin pesos", np.ones(n)), ("w exacto", w_true(xs)),
                 ("w estimado", w_est), ("w estimado ^ 0.5", np.sqrt(w_est))]:
        b = weighted_ls(xs, ys, w)
        mse[k].append(np.mean((yt - b[0] - b[1] * xt) ** 2))
    neff.append(w_est.sum() ** 2 / (w_est ** 2).sum())

for k, v in mse.items():
    print(f"{k:17s} ECM en destino {np.mean(v):.3f} ± {np.std(v):.3f}")
ES_w2 = np.mean(w_true(rng.normal(mS, sS, 10**6)) ** 2)
print(f"n_eff medio con w estimado: {np.mean(neff):.1f} de n = {n};  n / E_S[w²] = {n / ES_w2:.1f}")
xx = rng.normal(mT, sT, 10**6)
b = np.polyfit(xx, f(xx), 1)
print(f"mejor recta posible en destino: ECM = {np.mean((f(xx) - np.polyval(b, xx)) ** 2) + 0.09:.3f} (con el ruido 0.09)")

# Control: si la verdad es una recta, el modelo está bien especificado y los pesos solo añaden varianza
g = lambda x: 1 - 2 * x
ctrl = {"sin pesos": [], "w exacto": []}
for rep in range(200):
    xs = rng.normal(mS, sS, n); ys = g(xs) + rng.normal(0, 0.3, n)
    for k, w in [("sin pesos", np.ones(n)), ("w exacto", w_true(xs))]:
        b = weighted_ls(xs, ys, w)
        ctrl[k].append(np.mean((g(xt) + rng.normal(0, 0.3, 20000) - b[0] - b[1] * xt) ** 2))
print("bien especificado:", {k: round(float(np.mean(v)), 4) for k, v in ctrl.items()})

Without weights, the line fits source region x≈0.5x \approx 0.5 and has target MSE 0.32 averaged over 200 runs. Exact weights bring it down to 0.096, close to the best target line’s 0.094, including 0.09 irreducible noise. Classifier-estimated weights give nearly the same result because quadratic logistic features include the true ratio. The flattened variant w^1/2\hat w^{1/2} lies between uniform and exact weighting. Effective sample size is about 61 out of 150, close to n/ES[w2]≈63n/\E_S[w^2] \approx 63. The control matches Shimodaira’s analysis: when correctly specified, weighting increases error from 0.0915 to 0.0927 by adding variance.

The library version uses classifier probabilities and the sample_weight argument supported by most relevant scikit-learn estimators.

[ ]The same workflow with scikit-learnBrowser
from sklearn.linear_model import LogisticRegression, LinearRegression

xs = rng.normal(mS, sS, n); ys = f(xs) + rng.normal(0, 0.3, n); xu = rng.normal(mT, sT, m)
Xd = np.r_[xs, xu]
dom = LogisticRegression(C=1e6, max_iter=1000).fit(np.c_[Xd, Xd**2], np.r_[np.zeros(n), np.ones(m)])
p = dom.predict_proba(np.c_[xs, xs**2])[:, 1]
w = (n / m) * p / (1 - p)
for nombre, sw in [("sin pesos", None), ("ponderado", w)]:
    reg = LinearRegression().fit(xs[:, None], ys, sample_weight=sw)
    print(f"{nombre:10s} ECM en destino {np.mean((yt - reg.predict(xt[:, None])) ** 2):.3f}")

Byrd and Lipton (2019) find that in deep networks that eventually separate training data, importance weights matter early and their effect fades over epochs. L2 regularization and batch normalization partly restore it, while dropout does not in their experiments. The implicit regularization lesson explains the intuition. Once all training losses nearly vanish, scaling them by different constants can have little effect on the limit of gradient descent.

The cost of weighting: variance, effective sample size, and Rényi divergence

Unbiased R^w\hat R_w can still have high variance. The variance determines how useful it is at finite nn. For ℓ∈[0,1]\ell \in [0, 1] and fixed hh,

Var⁡(R^w(h))=ES[w2ℓ2]−RT(h)2n≤ES[w2]n.\Var\big(\hat R_w(h)\big) = \frac{\E_S[w^2\ell^2] - R_T(h)^2}{n} \le \frac{\E_S[w^2]}{n}.

The second moment of the weights is a divergence between the distributions.

Cortes, Mansour and Mohri (2010) use base 2: d2(P ∥ Q)=2D2(P∥Q)=EQ[w2]d_2(P \,\|\, Q) = 2^{D_2(P \| Q)} = \E_Q[w^2] in Lemma 1. neffn_{\text{eff}} comes from survey statistics. If i.i.d. values have variance s2s^2 with fixed weights wiw_i, the self-normalized estimate ∑iwivi/∑iwi\sum_i w_i v_i/\sum_i w_i has variance s2∑iwi2/(∑iwi)2=s2/neffs^2\sum_i w_i^2/(\sum_i w_i)^2 = s^2/n_{\text{eff}}, equal to the variance of an unweighted mean of neffn_{\text{eff}} observations. The importance sampling lesson uses the same statistic.

Gaussian case. For source N(0,1)N(0, 1) and target N(μ,1)N(\mu, 1), w(x)=eμx−μ2/2w(x) = e^{\mu x - \mu^2/2} and

ES[w2]=E[e2μX−μ2]=e2μ2−μ2=eμ2,\E_S[w^2] = \E\big[e^{2\mu X - \mu^2}\big] = e^{2\mu^2 - \mu^2} = e^{\mu^2},

using E[etX]=et2/2\E[e^{tX}] = e^{t^2/2}. Thus D2=μ2D_2 = \mu^2 and neff≈ne−μ2n_{\text{eff}} \approx n e^{-\mu^2}. Shifting the target by two standard deviations divides effective sample size by e4≈55e^4 \approx 55, and three divides it by more than 8000. Overlap alone does not control variance. For source N(0,s2)N(0, s^2) and target N(0,1)N(0, 1), supports are identical, but

ES[w2]=s2 E[e(1/s2−1)X2]=s22s2−1si s2>12,ES[w2]=∞si s2≤12,\E_S[w^2] = s^2\,\E\big[e^{(1/s^2 - 1)X^2}\big] = \frac{s^2}{\sqrt{2s^2 - 1}} \quad\text{si } s^2 > \tfrac12, \qquad \E_S[w^2] = \infty \quad\text{si } s^2 \le \tfrac12,

because E[etX2]=(1−2ts2)−1/2\E[e^{tX^2}] = (1 - 2ts^2)^{-1/2} exists only for t<1/(2s2)t < 1/(2s^2). A narrow source gives little mass to the target’s tails, so the few sampled points there receive very large weights. Cortes et al., Section 4.1, give condition σQ2>σP2/2\sigma_Q^2 > \sigma_P^2/2 with QQ as source and PP as target.

InteractiveEffective sample size collapse
  • source N(0,1)N(0, 1)
  • target N(μ,1)N(\mu, 1)
  • stem height 0.6wi/∑jwj0.6\sqrt{w_i / \sum_j w_j}
  • classification errors occur for x>1x > 1
  • prediction e^(−μ²)
  • Kish (median of 40)
The 200 estimates of RTR_T (dots), their mean ± one standard deviation (bar), and the true value (line)
0.00.51.01.5≥ 2R_T = 0.691
1.50
Source sample size
Estimator of RTR_T
ES[w2]=eμ2\mathbb{E}_S[w^2] = e^{\mu^2}9.49
ne−μ2n e^{-\mu^2} (prediction)105.4
Kish neffn_{\text{eff}} (sample 1)123.0
Largest normalized weight5.3 %
Mean ± standard deviation of 200 estimates0.687 ± 0.097
Bias and RMSE−0.005 and 0.097
Source N(0,1)N(0, 1), target N(μ,1)N(\mu, 1), exact weights w(x)=eμx−μ2/2w(x) = e^{\mu x - \mu^2/2}. A fixed classifier errs when x>1x > 1 (red), so RT=PT(X>1)=Φ(μ−1)R_T = \Pr_T(X > 1) = \Phi(\mu - 1). Top left: densities and the 260 most heavily weighted points of the first source sample. Each magenta stem is 0.6wi/∑jwj0.6\sqrt{w_i/\sum_j w_j} high. The square root makes both 0.1% and 50% weights visible. A stem reaching 0.6 would carry all the weight. At right: Kish neff/nn_{\text{eff}}/n (median of 40 samples) against e−μ2e^{-\mu^2} on a log scale. Bottom: 200 independent estimates of RTR_T, each using nn source points, with mean ± one standard deviation. Initially μ=1.5\mu = 1.5 and n=1000n = 1000, about 105 effective points with a widely dispersed estimator. Raise μ\mu to 3. Most estimates fall below RTR_T and a few far exceed it. Then clip at τ\tau or switch to self-normalization.

The next cell uses 2000 samples of n=1000n = 1000 at each μ\mu and compares three estimators of RTR_T: weighted 1n∑iwiℓi\frac1n\sum_i w_i\ell_i, self-normalized ∑iwiℓi/∑iwi\sum_i w_i\ell_i/\sum_i w_i, and clipped 1n∑imin⁡(wi,τ)ℓi\frac1n\sum_i \min(w_i, \tau)\ell_i with τ=10\tau = 10.

[ ]Importance weights: effective sample size and estimator varianceBrowser
import numpy as np
from scipy.stats import norm

rng = np.random.default_rng(0)
n, reps = 1000, 2000
Z = rng.standard_normal((reps, n))        # 2000 muestras de origen N(0, 1) de tamaño n
loss = (Z > 1).astype(float)              # el clasificador fijo falla cuando x > 1

print(" mu   E_S[w²]  n·e^(-mu²)  Kish(mediana)   R_T   | ponderado: media ± sd (mediana) | autonorm.: media ± sd | recorte τ=10: media ± sd")
for mu in [0.5, 1.0, 1.5, 2.0, 2.5, 3.0]:
    w = np.exp(mu * Z - mu**2 / 2)        # p_T / p_S exacto
    R_T = norm.cdf(mu - 1)
    iw = (w * loss).mean(axis=1)
    sn = (w * loss).sum(axis=1) / w.sum(axis=1)
    cl = (np.minimum(w, 10.0) * loss).mean(axis=1)
    kish = w.sum(axis=1) ** 2 / (w**2).sum(axis=1)
    print(f"{mu:3.1f} {np.exp(mu**2):9.1f} {n * np.exp(-mu**2):10.1f} {np.median(kish):12.1f} {R_T:8.3f}   |"
          f"   {iw.mean():.3f} ± {iw.std():.3f} ({np.median(iw):.3f})    |   {sn.mean():.3f} ± {sn.std():.3f}     |"
          f"   {cl.mean():.3f} ± {cl.std():.3f}")

Three patterns emerge. The unbiased weighted estimator can be unreliable at large μ\mu. With μ=2\mu = 2 its mean is 0.843 against RT=0.841R_T = 0.841, with standard deviation 0.220. At μ=3\mu = 3 some probability estimates exceed 1. Its median lies below RTR_T because a few samples with one huge weight sustain the mean. A typical run underestimates risk. The diagnostic neffn_{\text{eff}} can also be misleading. At μ=2\mu = 2 the prediction is 1000 e−4≈181000\,e^{-4} \approx 18 and the Kish median is 52. At μ=3\mu = 3 the prediction is 0.1, below one effective point, while Kish gives about 12. Empirical neffn_{\text{eff}} is a ratio of heavy-tailed sums. When events dominating ES[w2]\E_S[w^2] are too rare to sample, the diagnostic overestimates precision. Low neffn_{\text{eff}} flags a problem, and high values offer no guarantee. Clipping trades variance for bias. With τ=10\tau = 10 and μ=2\mu = 2 the standard deviation falls from 0.220 to 0.054, and the mean falls to 0.560 against 0.841. The self-normalized estimator, biased at finite O(1/n)\bigO(1/n), has the smallest spread in this case, partly because loss is 1 where weight concentrates. This need not generalize.

The next cell checks the shared-support case with infinite variance.

[ ]Identical supports with infinite weight varianceBrowser
rng = np.random.default_rng(1)
for s in [0.8, 0.6]:
    x = s * rng.standard_normal(10**6)                 # origen N(0, s²); destino N(0, 1)
    w = norm.pdf(x) / norm.pdf(x, scale=s)
    teo = s**2 / np.sqrt(2 * s**2 - 1) if s**2 > 0.5 else np.inf
    parciales = [np.mean(w[:k] ** 2) for k in (10**3, 10**4, 10**5, 10**6)]
    print(f"s = {s}: E_S[w²] teórico = {teo:.3f}; media de w² con 1e3, 1e4, 1e5 y 1e6 muestras:", np.round(parciales, 3))

At s=0.8s = 0.8 the empirical mean of w2w^2 stabilizes near 1.209. At s=0.6s = 0.6 (s2=0.36<1/2s^2 = 0.36 < 1/2) it rises from 2.1 to 6.6, 7.2 and 8.9 as the sample grows geometrically by factors of ten. New extremes cause jumps. The finite-variance guarantee fails regardless of sample size.

Learning guarantees for weighted samples

Cortes, Mansour and Mohri turn weight variance into bounds. When weights are bounded by M=sup⁡xw(x)M = \sup_x w(x), Hoeffding gives ∣R(h)−R^w(h)∣≤Mlog⁡(2/δ)/(2n)\abs{R(h) - \hat R_w(h)} \le M\sqrt{\log(2/\delta)/(2n)} (Proposition 1), with MM in place of 1 in the test-set bound. Bernstein improves that dependence. With probability at least 1−δ1 - \delta for fixed hh (Theorem 1 with α=1\alpha = 1),

RT(h)≤R^w(h)+2Mlog⁡(1/δ)3n+2 d2(PT ∥ PS)log⁡(1/δ)n.R_T(h) \le \hat R_w(h) + \frac{2M\log(1/\delta)}{3n} + \sqrt{\frac{2\,d_2(P_T \,\|\, P_S)\log(1/\delta)}{n}}.

Variance term d2/n\sqrt{d_2/n} dominates and behaves like a sample of n/d2=ne−D2n/d_2 = n e^{-D_2} points. For a finite class add log⁡∣H∣\log\abs{\Hyp} to log⁡(1/δ)\log(1/\delta) (Theorem 2). Proposition 2 gives a matching obstruction. If the class contains a constant-loss-1 hypothesis, with probability bounded below the uniform deviation sup⁡h∣RT(h)−R^w(h)∣\sup_h \abs{R_T(h) - \hat R_w(h)} exceeds (d2−1)/(4n)\sqrt{(d_2 - 1)/(4n)}. Hence dependence on d2d_2 is necessary. Theorem 3 also handles unbounded weights when d2<∞d_2 < \infty, with a slower rate in nn (exponent 3/83/8 instead of 1/21/2). At d2=∞d_2 = \infty these bounds fail. Their Gaussian mixture example in Figure 1 shows weighted ERM near 50% error with 5000 points when the source scale is 0.3 times the target scale. It learns successfully at ratio 0.75. Condition 0.752>1/2>0.320.75^2 > 1/2 > 0.3^2 separates the cases.

Clipping weights (w↦min⁡(w,τ)w \mapsto \min(w, \tau)) bounds MM and variance at the cost of bias ES[(w−τ)+ℓ]\E_S[(w - \tau)_+\ell], the target mass left uncorrected. Cortes et al. caution that arbitrary clipping can hurt and propose choosing weights through an explicit bias–variance trade-off.

Label shift and target class proportions

With label shift the unknown is a vector of KK numbers rather than a function of xx. Write py=PS(Y=y)p_y = P_S(Y = y), qy=PT(Y=y)q_y = P_T(Y = y) and wy=qy/pyw_y = q_y/p_y. Since pT(x∣y)=pS(x∣y)p_T(x \given y) = p_S(x \given y), we have pT(x,y)=wy pS(x,y)p_T(x, y) = w_y\,p_S(x, y). Dividing by pT(x)=∑kwk pS(x,k)p_T(x) = \sum_k w_k\,p_S(x, k) gives

PT(y∣x)=wy PS(y∣x)∑kwk PS(k∣x).P_T(y \given x) = \frac{w_y\,P_S(y \given x)}{\sum_k w_k\,P_S(k \given x)}.

With known qq, multiply each source posterior by wyw_y and renormalize to obtain the target Bayes classifier without retraining, by the Bayes decision rule for the new priors. With two classes, add log⁡(w1/w0)\log(w_1/w_0) to the logit, as in the prior correction in the first figure. The challenge is estimating qq with unlabeled target data.

BBSE and identifiability from a confusion matrix

Take any fixed classifier ff, even one with poor accuracy or calibration, and write y^=f(x)\hat y = f(x). Since y^\hat y depends on yy only through xx and p(x∣y)p(x \given y) is unchanged, p(y^∣y)p(\hat y \given y) is also unchanged. The law of total probability gives

PT(y^=i)=∑jP(y^=i∣y=j) qj=∑jPS(y^=i,y=j)⏟Cij wj,es decirμ=Cw,P_T(\hat y = i) = \sum_{j} P(\hat y = i \given y = j)\,q_j = \sum_j \underbrace{P_S(\hat y = i, y = j)}_{C_{ij}}\,w_j, \qquad\text{es decir}\qquad \vb{\mu} = \mat{C}\vb{w},

where μ\vb{\mu} is the target prediction distribution, estimated from mm unlabeled inputs. C\mat{C} is the joint source confusion matrix, estimated on labeled validation data.

Label shift estimation by BBSE, short for black box shift estimation, plugs in counts: C^ij=1n∑l1[f(xl)=i,yl=j]\hat{\mat{C}}_{ij} = \frac{1}{n}\sum_l \ind[f(\vb{x}_l) = i, y_l = j] on source validation, μ^i=1m∑l1[f(xl′)=i]\hat\mu_i = \frac1m\sum_l \ind[f(\vb{x}'_l) = i] on the target, and w^=C^−1μ^\hat{\vb{w}} = \hat{\mat{C}}^{-1}\hat{\vb{\mu}}. Lipton, Wang and Smola (2018) prove consistency in Proposition 2. If (A.3) holds with separation from singularity and σmin⁡\sigma_{\min} is the smallest singular value of C\mat{C}, their Theorem 3 gives with high probability

∥w^−w∥22≤Cσmin⁡2(∥w∥22log⁡nn+Klog⁡mm).\norm{\hat{\vb{w}} - \vb{w}}_2^2 \le \frac{C}{\sigma_{\min}^2}\left(\frac{\norm{\vb{w}}_2^2\log n}{n} + \frac{K\log m}{m}\right).

Confusing two classes makes σmin⁡\sigma_{\min} small. Squared error scales as its inverse square. Noise comes from source validation (nn) and the target sample (mm). Negative estimated weights from sampling error are often clipped to zero. The theorem’s last result is their Proposition 4. Comparing prediction distributions across domains gives a label shift test requiring no target labels.

Saerens’ EM algorithm

The maximum-likelihood alternative is due to Saerens, Latinne and Decaestecker (2002). If target inputs follow mixture pT(x)=∑yqy p(x∣y)p_T(x) = \sum_y q_y\,p(x \given y) with fixed components, the log likelihood of mm inputs is, up to constants independent of qq,

L(q)=∑l=1mlog⁡∑yqypy PS(y∣xl′),L(q) = \sum_{l=1}^m \log\sum_y \frac{q_y}{p_y}\,P_S(y \given \vb{x}'_l),

EM alternates using the current priors to compute posteriors P^(t)(y∣xl′)∝(qy(t)/py) PS(y∣xl′)\hat P^{(t)}(y \given \vb{x}'_l) \propto (q^{(t)}_y/p_y)\,P_S(y \given \vb{x}'_l) and averaging them for new priors qy(t+1)=1m∑lP^(t)(y∣xl′)q^{(t+1)}_y = \frac1m\sum_l \hat P^{(t)}(y \given \vb{x}'_l). LL is concave in qq, a sum of logs of linear functions, so EM can reach the simplex maximum from an interior initialization under the usual regularity conditions. It uses source probabilities and needs a calibrated classifier, while BBSE uses decisions. Alexandari, Kundaje and Shrikumar (2020) show that maximum likelihood with class-dependent bias correction outperforms BBSE on several datasets and shifts, while uncalibrated probabilities can cause it to fail. Classifier calibration is part of the procedure.

InteractiveBBSE step by step
  • source priors pp
  • true qq (drag)
  • q^\hat q BBSE
  • q^\hat q EM
1. Source confusion matrix
Across 1500 held-out source examples, C^ij=P^S(y^=i,y=j)\hat C_{ij} = \hat P_S(\hat y = i, y = j). The estimated matrix is invertible.
true y →0.4610.0350.0490.0310.2210.0360.0250.0190.122ŷ=1ŷ=2ŷ=3y=1y=2y=3
  • BBSE
  • EM
1. Source confusion matrix
2000
True qq0.20 · 0.20 · 0.60
BBSE q^\hat q0.18 · 0.22 · 0.59
EM q^\hat q0.20 · 0.22 · 0.58
Uncorrected target accuracy71.7 %
Accuracy with BBSE / EM80.7 % / 80.8 %
With true qq (oracle)80.8 %
Three classes in the plane with x∣y∼N(μy,I)x \given y \sim N(\vb{\mu}_y, \mat{I}), means (−1.3,−0.5)(-1.3, -0.5), (1.3,−0.5)(1.3, -0.5) and (0,1.2)(0, 1.2), and source priors p=(0.5,0.3,0.2)p = (0.5, 0.3, 0.2). The black box is the source Bayes classifier. Play four stages: joint confusion matrix from 1500 labeled source validation examples, prediction distribution on mm unlabeled target inputs, system solve, and posterior correction. Each triangle point is a vector of proportions. The open blue point is the source, the dark filled point the true target (drag it), and from step 3 the magenta and teal points are BBSE and EM. EM uses exact calibrated posteriors here. Below: ∥q^−q∥1\norm{\hat q - q}_1 versus mm, median of 12 repetitions. Initially q=(0.2,0.2,0.6)q = (0.2, 0.2, 0.6), making class 3 the majority. At m=2000m = 2000 correction raises accuracy from 71.7% to 80.7% (BBSE), 80.8% (EM), and 80.8% with the oracle. Vary mm to see where BBSE plateaus.

The EM error falls like 1/m1/\sqrt{m} across the plot. The BBSE error flattens at large mm because of the log⁡n/n\log n/n term for confusion-matrix noise from 1500 source validation examples. Additional target inputs cannot reduce that term. EM avoids it here with exact posteriors. The second lab implements both methods on this model.

[ ]BBSE and EM from scratchBrowser
import numpy as np

MU = np.array([[-1.3, -0.5], [1.3, -0.5], [0.0, 1.2]])
p = np.array([0.5, 0.3, 0.2]); K = 3

def sample(rng, m, pri):
    y = rng.choice(K, size=m, p=pri)
    return MU[y] + rng.standard_normal((m, 2)), y

def posterior(X, pri):
    L = np.log(pri) - 0.5 * ((X[:, None, :] - MU[None]) ** 2).sum(-1)
    E = np.exp(L - L.max(1, keepdims=True))
    return E / E.sum(1, keepdims=True)

def bbse(yhat_val, y_val, yhat_tgt, K):
    C = np.zeros((K, K))
    np.add.at(C, (yhat_val, y_val), 1)
    C /= len(y_val)                                        # C_ij = P_S(ŷ = i, y = j)
    mu = np.bincount(yhat_tgt, minlength=K) / len(yhat_tgt)  # P_T(ŷ = i)
    return np.clip(np.linalg.lstsq(C, mu, rcond=None)[0], 0, None)

def em_saerens(P_src, p_src, iters=1000, tol=1e-7):
    q = p_src.copy()
    for _ in range(iters):
        A = P_src * (q / p_src)
        A /= A.sum(1, keepdims=True)                       # paso E: posteriores con los priors actuales
        q_new = A.mean(0)                                  # paso M: priors nuevos
        if np.abs(q_new - q).max() < tol:
            return q_new
        q = q_new
    return q

rng = np.random.default_rng(0)
Xv, yv = sample(rng, 1500, p)
yhat_v = posterior(Xv, p).argmax(1)                        # caja negra: Bayes de origen
q = np.array([0.2, 0.2, 0.6])
print("     m   ‖q̂−q‖₁ BBSE   ‖q̂−q‖₁ EM    exactitud: sin corregir / BBSE / EM / q verdadero")
for m in [100, 1000, 10000]:
    res = []
    for r in range(20):
        Xt, yt = sample(rng, m, q)
        Pt = posterior(Xt, p)
        w = bbse(yhat_v, yv, Pt.argmax(1), K)
        qe = em_saerens(Pt, p)
        acc = lambda wy: np.mean((Pt * wy).argmax(1) == yt)
        res.append([np.abs(w * p - q).sum(), np.abs(qe - q).sum(), acc(np.ones(K)), acc(w), acc(qe / p), acc(q / p)])
    a = np.mean(res, axis=0)
    print(f"{m:6d}      {a[0]:.3f}         {a[1]:.3f}         {a[2]:.3f} / {a[3]:.3f} / {a[4]:.3f} / {a[5]:.3f}")

Accuracy rises from 0.71 to 0.81, matching correction with true qq. The gain appears at m=100m = 100 even though the error in qq is still large (0.20 in ℓ1\ell_1 norm for BBSE). Decisions only change near boundaries, where the sign of the change matters. At m=10 000m = 10\,000, BBSE error 0.050 is three times EM error 0.016, reflecting the source confusion matrix estimated on 1500 examples.

The real-data lab uses scikit-learn’s digits, images of size 8×88\times 8 for ten digits. This is an anticausal problem because the intended digit determines the image. The classifier is logistic regression on six principal components to leave room for improvement. To simulate imbalanced target priors, draw from Dirichlet(0.5,…,0.5)(0.5, \dots, 0.5) and resample each class from a partition the classifier has not seen. This preserves p(x∣y)p(x \given y).

[ ]Digits with different class proportionsBrowser
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression

X, y = load_digits(return_X_y=True)
K = 10
rows = []
for seed in range(10):
    rng = np.random.default_rng(seed)
    idx = rng.permutation(len(y))
    tr, va, te = idx[:700], idx[700:1100], idx[1100:]      # entrenamiento, validación de origen, reserva para el destino
    Zf = PCA(6).fit(X[tr]).transform(X)
    clf = LogisticRegression(max_iter=2000).fit(Zf[tr], y[tr])
    p_src = np.bincount(y[tr], minlength=K) / len(tr)
    q = rng.dirichlet(0.5 * np.ones(K))
    yt = rng.choice(K, size=2000, p=q)
    it = np.array([rng.choice(te[y[te] == k]) for k in yt])  # mismo p(x|y), proporciones q
    Pt = clf.predict_proba(Zf[it])
    w = bbse(clf.predict(Zf[va]), y[va], Pt.argmax(1), K)
    qb = w * p_src / (w * p_src).sum()
    qe = em_saerens(Pt, p_src)
    acc = lambda wy: np.mean((Pt * wy).argmax(1) == yt)
    rows.append([acc(np.ones(K)), acc(w), acc(qe / p_src), acc(q / p_src), np.abs(qb - q).sum(), np.abs(qe - q).sum()])
a = np.mean(rows, axis=0)
print(f"exactitud media en destino: sin corregir {a[0]:.3f} | BBSE {a[1]:.3f} | EM {a[2]:.3f} | q verdadero {a[3]:.3f}")
print(f"error ‖q̂ − q‖₁ medio: BBSE {a[4]:.3f} | EM {a[5]:.3f}")

Across ten draws, correction increases accuracy from 0.860 to 0.888 with BBSE and 0.891 with EM, versus 0.894 with true proportions. EM estimates qq with about half the error of BBSE (0.094 versus 0.181 in ℓ1\ell_1 norm). The lightly regularized logistic regression is reasonably calibrated, and the ten-class confusion matrix from 400 validation examples is noisy. Repeat with LogisticRegression(C=0.01) to flatten probabilities and compare how estimates of qq degrade. EM depends on calibration, whereas BBSE uses only decisions.

Ben-David et al.’s domain adaptation bound

Without assuming either type of shift, we can ask how much a hypothesis trained on the source can degrade, in terms measurable without target labels. Ben-David, Blitzer, Crammer, Kulesza, Pereira and Wortman Vaughan (2010) study binary classification with deterministic labels fSf_S and fTf_T. They write ϵD(h,h′)=Px∼D[h(x)≠h′(x)]\epsilon_D(h, h') = \Pr_{x \sim D}[h(x) \neq h'(x)] for disagreement between two functions under marginal DD, giving ϵS(h)=ϵS(h,fS)\epsilon_S(h) = \epsilon_S(h, f_S).

Their Theorem 1 uses total variation d1(DS,DT)=2sup⁡B∣PDS(B)−PDT(B)∣d_1(D_S, D_T) = 2\sup_B\abs{\Pr_{D_S}(B) - \Pr_{D_T}(B)} to give ϵT(h)≤ϵS(h)+d1(DS,DT)+min⁡{EDS∣fS−fT∣,EDT∣fS−fT∣}\epsilon_T(h) \le \epsilon_S(h) + d_1(D_S, D_T) + \min\{\E_{D_S}\abs{f_S - f_T}, \E_{D_T}\abs{f_S - f_T}\}. In general d1d_1 cannot be estimated reliably from finite samples. It can also be pessimistic because it ranges over all measurable sets, including those the hypothesis class cannot distinguish.

One direct consequence is enough to prove the adaptation bound.

Proof

ϵD(h,h′)=PD[(h⊕h′)(x)=1]\epsilon_D(h, h') = \Pr_D[(h \oplus h')(x) = 1] and h⊕h′∈HΔHh \oplus h' \in \Hyp\Delta\Hyp, so ∣ϵS(h,h′)−ϵT(h,h′)∣\abs{\epsilon_S(h, h') - \epsilon_T(h, h')} contributes one candidate to the supremum defining 12dHΔH\frac12 d_{\Hyp\Delta\Hyp}.

∎

The first inequality follows from three uses of triangle inequality ϵ(f1,f2)≤ϵ(f1,f3)+ϵ(f3,f2)\epsilon(f_1, f_2) \le \epsilon(f_1, f_3) + \epsilon(f_3, f_2) and Lemma 3, through h∗h^*. The guided proof develops it step by step. The finite-sample version replaces dHΔHd_{\Hyp\Delta\Hyp} by its empirical estimate using uniform convergence from Lemma 1 and the VC dimension bound HΔH\Hyp\Delta\Hyp of at most 2d2d.

ϵS(h)\epsilon_S(h) is the source error minimized by ERM. Divergence measures how much pairs of hypotheses can change their disagreement across domains and is estimable without target labels. λ∗\lambda^* measures how well a single hypothesis can do on both domains. If all hypotheses fit at most one domain well, the guarantee reflects that limitation. However, λ∗\lambda^* depends on fTf_T, so assuming a small joint error requires information beyond unlabeled target data.

Estimating divergence with a domain discriminator

Lemma 2 expresses divergence as a classification problem. Suppose G\mathcal{G} is symmetric under complementation. Label each example in USU_S as 0 and each in UTU_T as 1. A classifier g∈Gg \in \mathcal{G} calling set AA target has balanced error ϵ(g)=12[PUS(A)+1−PUT(A)]\epsilon(g) = \frac12[\Pr_{U_S}(A) + 1 - \Pr_{U_T}(A)]. Minimizing over G\mathcal{G} gives

min⁡gϵ(g)=12−12sup⁡A(PUT(A)−PUS(A))=12−14d^G⟹d^G=2(1−2min⁡gϵ(g)).\min_g \epsilon(g) = \frac12 - \frac12\sup_A\big(\Pr_{U_T}(A) - \Pr_{U_S}(A)\big) = \frac12 - \frac14\hat d_{\mathcal{G}} \quad\Longrightarrow\quad \hat d_{\mathcal{G}} = 2\big(1 - 2\min_g\epsilon(g)\big).

A chance discriminator (ϵ=1/2\epsilon = 1/2) gives distance 0. A perfect discriminator (ϵ=0\epsilon = 0) gives the maximum 2. In practice this is called the proxy distance d^A=2(1−2ϵ)\hat d_A = 2(1 - 2\epsilon). In Section 7 the authors note that a trained linear classifier gives a lower bound on d^H\hat d_{\Hyp} because it may miss the best discriminator, and that quantity is itself below d^HΔH\hat d_{\Hyp\Delta\Hyp}. The error guarantee needs an upper bound, which is computationally hard for half-spaces. A proxy alone does not certify the guarantee.

InteractiveMeasuring divergence with a discriminator
  • source
  • target
  • region classified as target
  • hSh_S
  • h∗h^* (oracle)
  • RS(hS)R_S(h_S)
  • 12d^\tfrac12 \hat d
  • λ∗\lambda^*
  • RT(hS)R_T(h_S)
boundobserved R_T(h_S)10
Discriminator class
Target labels
Target spread
Balanced discriminator error ϵ\epsilon17.7 %
d^HΔH=2(1−2ϵ)\hat d_{\mathcal{H}\Delta\mathcal{H}} = 2(1 - 2\epsilon)1.292
RS(hS)R_S(h_S)9.7 %
λ∗=RS(h∗)+RT(h∗)\lambda^* = R_S(h^*) + R_T(h^*)22.2 %
Bound RS+12d^+λ∗R_S + \tfrac12\hat d + \lambda^*96.4 %
Observed RT(hS)R_T(h_S)26.9 %
∣ϵS(hS,h∗)−ϵT(hS,h∗)∣|\epsilon_S(h_S, h^*) - \epsilon_T(h_S, h^*)|0.103
1200 source points from N(0,I)N(\vb{0}, \mat{I}) (blue) and 1200 target points (orange). Labels are y=1[x2>0.35(x12−1)]y = \ind[x_2 > 0.35(x_1^2 - 1)] in both domains (gray boundary), or the target parabola is rotated by 40°. H\Hyp denotes half-spaces. hSh_S (blue) minimizes source 0–1 error. Oracle h∗h^* (purple dashed) uses target labels and minimizes ϵS+ϵT\epsilon_S + \epsilon_T. The discriminator searches for the set AA that best separates the sampled domains. The shaded area is called target. Its class can be half-spaces or two-half-space symmetric differences {u1>t1}⊕{u2>t2}\{u_1 > t_1\} \oplus \{u_2 > t_2\} of HΔH\Hyp\Delta\Hyp, tested over 24 directions and 21 quantile thresholds per line. The top bar stacks ϵS(hS)\epsilon_S(h_S), 12d^\frac12\hat d and λ∗\lambda^*, and the lower bar is actual target error. Drag the target center. At coincident domains d^\hat d need not be exactly zero because the empirical supremum over 1200 points has sampling bias, reflected in the square-root term. Try the more dispersed target with a linear discriminator.

The bound is loose. Initially with target center (1.5,1)(1.5, 1), term 12d^\frac12\hat d is already 0.65 and the bound is 0.96, while actual error is 0.27. Move the target away and the bound exceeds 1. The proof uses the particular pair (hS,h∗)(h_S, h^*) and ∣ϵS(hS,h∗)−ϵT(hS,h∗)∣\abs{\epsilon_S(h_S, h^*) - \epsilon_T(h_S, h^*)}. The final readout shows that their discrepancy is much lower than the supremum over pairs. Also, λ∗\lambda^* is sizable even without shift, since a half-space cannot fit the parabola. Finally, with the wider target N(mT,4I)N(\vb{m}_T, 4\mat{I}) and coincident centers, the best half-space detects less discrepancy than two lines around the source center. The measured discrepancy depends on discriminator capacity.

[ ]Proxy distance and the limits of a linear discriminatorBrowser
from sklearn.linear_model import LogisticRegression

rng = np.random.default_rng(0)
N = 2000

def proxy(XS, XT, feat):
    """Distancia proxy 2(1 - 2 ε) con el error ε de un discriminador logístico en una partición reservada."""
    Xd = np.r_[XS, XT]
    d = np.r_[np.zeros(len(XS)), np.ones(len(XT))]
    perm = rng.permutation(len(d)); tr, te = perm[: len(d) // 2], perm[len(d) // 2 :]
    clf = LogisticRegression(max_iter=1000).fit(feat(Xd[tr]), d[tr])
    eps = 1 - clf.score(feat(Xd[te]), d[te])
    return eps, 2 * (1 - 2 * eps)

lineal = lambda X: X
cuadratico = lambda X: np.c_[X, X**2, X[:, :1] * X[:, 1:]]
print("Destino desplazado N((δ, 0), I):   ε lineal, proxy lineal, d_1 exacta = 2(2Φ(δ/2) − 1)")
for delta in [0.5, 1, 2, 3]:
    XS = rng.standard_normal((N, 2)); XT = rng.standard_normal((N, 2)) + [delta, 0]
    e, dh = proxy(XS, XT, lineal)
    print(f"  δ = {delta}:  {e:.3f}  {dh:.3f}  {2 * (2 * norm.cdf(delta / 2) - 1):.3f}")
print("Destino más ancho N(0, s² I):   ε logístico lineal, su proxy | d_H del mejor semiplano | proxy cuadrático | d_1 exacta")
t = np.linspace(0, 8, 8001)
for s in [2, 3]:
    XS = rng.standard_normal((N, 2)); XT = s * rng.standard_normal((N, 2))
    e_lin, d_lin = proxy(XS, XT, lineal)
    d_H = 2 * np.max(norm.cdf(t) - norm.cdf(t / s))        # semiplano {u > t}: P_S - P_T = Φ(t) - Φ(t/s)
    r2 = 2 * s**2 * np.log(s**2) / (s**2 - 1)               # radio² donde se cruzan las densidades
    tv = np.exp(-r2 / (2 * s**2)) - np.exp(-r2 / 2)
    print(f"  s = {s}:  {e_lin:.3f}  {d_lin:.3f}  |  {d_H:.3f}  |  {proxy(XS, XT, cuadratico)[1]:.3f}  |  {2 * tv:.3f}")

With a mean shift, the linear discriminator recovers exact total variation d1=2(2Φ(δ/2)−1)d_1 = 2(2\Phi(\delta/2) - 1) up to sampling noise. For Gaussians with equal covariance, a half-space maximizes ∣PS(B)−PT(B)∣\abs{\Pr_S(B) - \Pr_T(B)}. Under scale shift, the best half-space {u>t}\{u > t\} with appropriate tt captures only dH=0.32d_{\Hyp} = 0.32 or 0.480.48 of the total variation 0.95 or 1.35. Logistic regression, trained on logistic rather than 0–1 loss, misses even this solution: errors are worse than chance (0.57 and 0.63), and proxy values turn negative. The surrogate can yield an estimate below d^H\hat d_{\Hyp}. Quadratic features recover total variation in this experiment.

What representation alignment can miss

The bound suggests learning a representation z=g(x)z = g(x) with indistinguishable source and target marginals and fitting a classifier hh on zz with low source error. Ganin et al. (2016) use this in domain-adversarial training (DANN). A domain classifier tries to distinguish representations and the extractor gg learns features that reduce its ability to do so. The representation can also change the bound’s third term λ∗\lambda^*.

Zhao, Tachet des Combes, Zhang and Gordon (2019) give a simple counterexample in Section 4.1. Source U(−1,0)U(-1, 0) has fS(x)=1[x>−1/2]f_S(x) = \ind[x > -1/2], and target U(1,2)U(1, 2) has fT(x)=1[x<3/2]f_T(x) = \ind[x < 3/2]. Interval hypothesis 1[−1/2<x<3/2]\ind[-1/2 < x < 3/2] classifies both perfectly, giving λ∗=0\lambda^* = 0 among interval hypotheses. The representation g(x)=x+1g(x) = x + 1 for x≤0x \le 0 and g(x)=x−1g(x) = x - 1 for x>0x > 0 maps both to U(0,1)U(0, 1), yielding perfect marginal alignment. But in zz labels reverse, with fS=1[z>1/2]f_S = \ind[z > 1/2] and fT=1[z<1/2]f_T = \ind[z < 1/2]. Every hh on zz therefore satisfies ϵS(h∘g)+ϵT(h∘g)=P[h≠fS]+P[h=fS]=1\epsilon_S(h \circ g) + \epsilon_T(h \circ g) = \Pr[h \neq f_S] + \Pr[h = f_S] = 1. Lower error on one domain implies higher error on the other.

Different label proportions give a general obstruction.

The limits of invariant representations follow. If label marginals differ but the representation aligns perfectly (dJS(PSZ,PTZ)=0d_{JS}(P_S^Z, P_T^Z) = 0), the sum of errors is at least 12DJS(PSY,PTY)\frac12 D_{JS}(P_S^Y, P_T^Y). Stricter alignment can raise the lower bound. Under label shift the target marginal zz naturally differs from the source because the mixing proportions change.

InteractiveAlignment alone can increase error
Source: py p(z∣y)p_y\, p(z \mid y) by class
Target, aligned representation
  • class y=0y = 0
  • class y=1y = 1
  • threshold cc
  • ε_S + ε_T, aligned
  • ε_S + ε_T with z = x
  • Zhao et al.’s bound (aligned)
Target representation
0.15
0.00
ϵS\epsilon_S (source)10.6 %
ϵT\epsilon_T (target)35.3 %
ϵS+ϵT\epsilon_S + \epsilon_T45.9 %
Zhao et al.’s lower bound (aligned z)5.2 %
Target Bayes error6.5 %
The zz marginals match. Positives are 15 % of the target and 50 % of the source. Alignment can shift class mass across the threshold. Without alignment, target error would be 10.6 %.
One dimension: x∣y=0∼N(−1,0.82)x \given y = 0 \sim N(-1, 0.8^2) and x∣y=1∼N(1,0.82)x \given y = 1 \sim N(1, 0.8^2), with PS(y=1)=0.5P_S(y = 1) = 0.5 and PT(y=1)=qP_T(y = 1) = q (pure label shift). The aligned representation keeps source z=xz = x and uses monotone transport z=FS−1(FT(x))z = F_S^{-1}(F_T(x)) on target inputs, making both marginal distributions of zz identical. The classifier predicts 1 for z>cz > c, and c=0c = 0 is source Bayes. Top: each class weighted by its prior in zz space for each domain. Bottom: ϵS+ϵT\epsilon_S + \epsilon_T versus qq for the chosen threshold, with alignment (red), z=xz = x (blue), and Zhao et al.’s bound 12DJS\frac12 D_{JS} for any aligned representation and threshold (purple). Initially q=0.15q = 0.15. Marginals match, but target class-0 mass occupies the source class-1 region in zz, and target error goes from 11% to over 35%. Switch to z=xz = x and move the threshold.

Impossibility results

Without assumptions linking fSf_S and fTf_T, consider two worlds with identical source data and identical target inputs but opposite target labels fTf_T and 1−fT1 - f_T. An algorithm sees the same data in both and returns the same hh. Since ϵT(h;fT)+ϵT(h;1−fT)=1\epsilon_T(h; f_T) + \epsilon_T(h; 1 - f_T) = 1, it incurs at least half error in one world. Ben-David, Lu, Luu and Pál (2010) study three conditions: covariate shift, small marginal divergence, and a hypothesis with small error on both domains (small λ∗\lambda^*). With unlabeled targets alone, covariate shift and small divergence are insufficient without small λ∗\lambda^*. Small λ∗\lambda^* also fails to suffice with large divergence. Their results limit source reweighting as a general solution and underscore the need for both terms in the adaptation guarantee.

Diagnosing shift before correcting it

  1. Consider causal direction. Does the label generate the input, as in diagnosis and recognition, or does the input cause the label? This informs whether label or covariate shift is plausible. The incompatibility theorem explains why the assumptions differ.
  2. Look for evidence. Train a sufficiently capable domain discriminator and evaluate on held-out inputs. AUC clearly above 0.5 indicates changed inputs. For label shift, compare prediction distributions from a fixed classifier across domains, as in Lipton et al., Proposition 4.
  3. Under label shift, estimate qq with BBSE or EM, using EM only with calibrated probabilities. Correct posteriors by multiplying by w^y\hat w_y, and monitor σmin⁡(C^)\sigma_{\min}(\hat{\mat{C}}).
  4. Under covariate shift, estimate ww from a domain classifier. Check neffn_{\text{eff}}, consider clipping or flattening, and run weighted cross-validation. Reweighting can help under misspecification.
  5. Collect a few labeled target examples. They let you measure λ∗\lambda^*, check for concept shift and evaluate the correction. Ben-David et al., Theorem 3, bound the error of ERM combining source and target risks with weight α\alpha. With optimal α\alpha, this bound is at most the better single-domain bound.

The next lesson on out-of-distribution generalization asks how to find one predictor that works across a family of possible targets.

Common mistakes

Exercises

ProofUnbiasedness of weighted risk
Prove: Under covariate shift, suppose pS(x)>0p_S(x) > 0 whenever pT(x)>0p_T(x) > 0, and let w=pT/pSw = p_T/p_S. For any fixed hh with finite RT(h)R_T(h), ES[w(X) ℓ(h(X),Y)]=RT(h)\E_S[w(X)\,\ell(h(X), Y)] = R_T(h).
0
Write target risk as the integral RT(h)=∫ ⁣ ⁣∫ℓ(h(x),y) pT(x,y) ⁣dy ⁣dxR_T(h) = \int\!\!\int \ell(h(x), y)\,p_T(x, y)\dd y\dd x.

Step 1 of 4. Which factorization of pT(x,y)p_T(x, y) should you use?

ProofThe Ben-David bound, step by step
Prove: For every h∈Hh \in \Hyp, ϵT(h)≤ϵS(h)+12dHΔH(DS,DT)+λ∗\epsilon_T(h) \le \epsilon_S(h) + \frac12 d_{\Hyp\Delta\Hyp}(D_S, D_T) + \lambda^*, where λ∗=ϵS(h∗)+ϵT(h∗)\lambda^* = \epsilon_S(h^*) + \epsilon_T(h^*) and h∗h^* is the ideal joint hypothesis.
0
Use the disagreement triangle inequality ϵD(f1,f2)≤ϵD(f1,f3)+ϵD(f3,f2)\epsilon_D(f_1, f_2) \le \epsilon_D(f_1, f_3) + \epsilon_D(f_3, f_2) for arbitrary functions and Lemma 3: ∣ϵS(h,h′)−ϵT(h,h′)∣≤12dHΔH\abs{\epsilon_S(h, h') - \epsilon_T(h, h')} \le \frac12 d_{\Hyp\Delta\Hyp} for h,h′∈Hh, h' \in \Hyp.

Step 1 of 4. What is the first step?

NumericEffective points after a mean shift
Source N(0,1)N(0, 1), target N(2,1)N(2, 1), and n=10 000n = 10\,000 source examples. Given ES[w2]=eμ2\E_S[w^2] = e^{\mu^2}, what is effective sample size ne−μ2n e^{-\mu^2}? Round to the nearest integer.
NumericA narrower source
Source N(0,s2)N(0, s^2) with s=0.75s = 0.75, target N(0,1)N(0, 1), and n=10 000n = 10\,000. What is effective sample size n/ES[w2]n/\E_S[w^2]? Round to the nearest integer.
QuizWhat BBSE requires
Which assumptions let BBSE identify target class proportions using a fixed classifier ff?
QuizWhat changed?
An X-ray pneumonia classifier trains at a general hospital and is deployed in another hospital’s emergency department during a flu outbreak. Equipment and acquisition protocol match, and pneumonia prevalence is three times as high. Which shift is most plausible in this scenario, and what correction follows under that assumption?
NumericComputing the bound with a discriminator
Classifier hh has source error 0.05. The best domain discriminator in HΔH\Hyp\Delta\Hyp has balanced error 0.15 on held-out data, and a small labeled target sample suggests λ∗≈0.10\lambda^* \approx 0.10. Ignoring finite-sample terms, what is the Ben-David et al. bound for ϵT(h)\epsilon_T(h)?
QuizA discriminator near chance
You train linear logistic regression to distinguish 20,000 source and 20,000 target inputs. Held-out accuracy is 50.3%. What can you conclude?
NumericThe lower bound under alignment
The positive class is 50% in the source and 10% in the target. If representation zz has identical marginals, what is Zhao et al.’s lower bound on ϵS+ϵT\epsilon_S + \epsilon_T? Use base-2 logarithms and give four decimal places.
QuizWhen can alignment hurt?
You train extractor gg with an adversarial term to match the source and target marginals of z=g(x)z = g(x). When is this most likely to increase target error?
CodeBBSE weights
Implement bbse_weights(confusion_source, pred_dist_target). Input confusion_source is the K×KK\times K joint source confusion matrix with C[i, j] = P_S(ŷ = i, y = j), and pred_dist_target is a length-KK vector with entries P_T(ŷ = i). Return the length-KK array w from Cw=μ\mat{C}\vb{w} = \vb{\mu} with negative components clipped at 0. For a singular or ill-conditioned matrix, for example when the classifier never predicts a class, return the clipped minimum-norm least-squares solution without raising an error.
import numpy as np

def bbse_weights(confusion_source, pred_dist_target):
  """Pesos w_y = q_y / p_y del cambio de etiquetas, no negativos."""
  C = np.asarray(confusion_source, dtype=float)
  mu = np.asarray(pred_dist_target, dtype=float)
  # tu código: resolver C w = mu de forma robusta y recortar los negativos
  return np.ones(len(mu))
Shift+Enter to run

Summary

Key idea
Adaptation requires assumptions about what changed. Under covariate shift, weighting by w=pT/pSw = p_T/p_S is unbiased and can help a misspecified model, with variance cost eD2(PT∥PS)e^{D_2(P_T \| P_S)}. Under label shift, solve μ=Cw\vb{\mu} = \mat{C}\vb{w} or use EM to estimate target proportions and update posteriors. The Ben-David et al. bound combines measurable divergence with joint error λ∗\lambda^*, which unlabeled target inputs do not identify. Matching representations can hurt when class proportions differ.
  • Factor the joint distribution as p(x)p(y∣x)p(x)p(y \given x) or p(y)p(x∣y)p(y)p(x \given y). Covariate shift preserves the first factorization’s conditional, label shift the second’s. They cannot both hold under nontrivial shifts except in degenerate cases. Causal direction informs the assumption.
  • Importance weighting is unbiased if PTX≪PSXP_T^X \ll P_S^X. A domain classifier estimates the ratio w=(n/m)elogitw = (n/m)e^{\text{logit}}. Shimodaira’s analysis shows when a well-specified model needs no weighting.
  • ES[w2]=eD2\E_S[w^2] = e^{D_2} and neff≈ne−D2n_{\text{eff}} \approx n e^{-D_2}. For N(0,1)→N(μ,1)N(0, 1) \to N(\mu, 1), ne−μ2n e^{-\mu^2}. Cortes, Mansour and Mohri’s bounds depend on d2d_2. With d2=∞d_2 = \infty, support overlap can still leave unbounded variance. Kish’s diagnostic can be optimistic, and clipping trades variance for bias.
  • Under label shift, PT(y∣x)∝wyPS(y∣x)P_T(y \given x) \propto w_y P_S(y \given x). BBSE solves w^=C^−1μ^\hat{\vb{w}} = \hat{\mat{C}}^{-1}\hat{\vb{\mu}} with a classifier whose confusion matrix is invertible (error ∝1/σmin⁡2\propto 1/\sigma_{\min}^2). Maximum-likelihood EM requires calibration.
  • ϵT(h)≤ϵS(h)+12dHΔH+λ∗\epsilon_T(h) \le \epsilon_S(h) + \frac12 d_{\Hyp\Delta\Hyp} + \lambda^*. A domain discriminator estimates divergence (d^=2(1−2ϵ)\hat d = 2(1 - 2\epsilon)). A linear discriminator can underestimate it, and λ∗\lambda^* requires target labels.
  • Zhao et al. show that with different label marginals, perfect alignment forces ϵS+ϵT≥12DJS(PSY,PTY)\epsilon_S + \epsilon_T \ge \frac12 D_{JS}(P_S^Y, P_T^Y). Ben-David et al. show that with unlabeled targets, both small divergence and small λ∗\lambda^* matter.