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
- 13Population (true) riskVC generalization boundRademacher generalization boundTest set boundExcess risk identities
- 04Radon-Nikodym theoremChange of measure
- 07Kullback-Leibler divergence (relative entropy)f-divergences
- 11Logistic regressionLogistic loss as Bernoulli likelihood
- 05Standard errorBayes rule and Bayes risk
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 differs from the deployment or target distribution 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: and are distributions on with densities and , or mass functions in the discrete case. Let and be risks of in the two domains. For 0–1 loss write and . We have labeled examples from and unlabeled inputs from .
Three ways a distribution can shift
Factor the joint distribution in two ways, . 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 and . Divide each by the corresponding factorization of . The ratio equals both , independent of , and , independent of . For inputs compatible with every class, all must have the same constant value . Since , we have . Then and, using , we get .
∎Choose the more plausible assumption before correcting a model. Schölkopf et al. (2012) give a criterion based on causal direction. If causes , as when a protein’s amino acid sequence determines how it folds, the causal mechanism can remain stable as sampled inputs change. Covariate shift is then natural. If causes , as when a disease produces symptoms or a writer’s intended digit produces an image, the stable mechanism is . Prevalence can vary across hospitals or populations, giving label shift. The structural causal models module formalizes this as mechanism invariance.
First, covariate shift increases error here because is misspecified. If the model could represent the parabola, the source Bayes classifier would remain optimal because stays fixed. The input shift changes where errors matter, so the linear model has to fit the target region. Second, for target center , readout gives . 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, 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 . It misses the target region absent from the source, even with unlimited source data. Unbiasedness also requires fixed . The minimizer depends on the sample, so 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 , 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 recovers unbiasedness.
Estimating a density ratio with a classifier
In practice and are unknown. Instead of fitting both high-dimensional densities, pool the source inputs with domain label and the target inputs with label . Fit a probabilistic domain classifier. Bayes’ rule under this mixture gives
With logistic regression on features , the population formula is exact when is linear in . For two Gaussian inputs, suffices, since their density ratio is the exponential of a quadratic. The quality of depends on probability calibration as well as classification performance.
The lab implements a regression example. The true function is with noise , and the fitted model is a line. The source is and target is . The ratio estimator uses 150 inputs per domain and a hand-written Newton solver for logistic regression.
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 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 lies between uniform and exact weighting. Effective sample size is about 61 out of 150, close to . 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.
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 can still have high variance. The variance determines how useful it is at finite . For and fixed ,
The second moment of the weights is a divergence between the distributions.
Cortes, Mansour and Mohri (2010) use base 2: in Lemma 1. comes from survey statistics. If i.i.d. values have variance with fixed weights , the self-normalized estimate has variance , equal to the variance of an unweighted mean of observations. The importance sampling lesson uses the same statistic.
Gaussian case. For source and target , and
using . Thus and . Shifting the target by two standard deviations divides effective sample size by , and three divides it by more than 8000. Overlap alone does not control variance. For source and target , supports are identical, but
because exists only for . 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 with as source and as target.
The next cell uses 2000 samples of at each and compares three estimators of : weighted , self-normalized , and clipped with .
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 . With its mean is 0.843 against , with standard deviation 0.220. At some probability estimates exceed 1. Its median lies below because a few samples with one huge weight sustain the mean. A typical run underestimates risk. The diagnostic can also be misleading. At the prediction is and the Kish median is 52. At the prediction is 0.1, below one effective point, while Kish gives about 12. Empirical is a ratio of heavy-tailed sums. When events dominating are too rare to sample, the diagnostic overestimates precision. Low flags a problem, and high values offer no guarantee. Clipping trades variance for bias. With and 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 , 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.
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 the empirical mean of stabilizes near 1.209. At () 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 , Hoeffding gives (Proposition 1), with in place of 1 in the test-set bound. Bernstein improves that dependence. With probability at least for fixed (Theorem 1 with ),
Variance term dominates and behaves like a sample of points. For a finite class add to (Theorem 2). Proposition 2 gives a matching obstruction. If the class contains a constant-loss-1 hypothesis, with probability bounded below the uniform deviation exceeds . Hence dependence on is necessary. Theorem 3 also handles unbounded weights when , with a slower rate in (exponent instead of ). At 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 separates the cases.
Clipping weights () bounds and variance at the cost of bias , 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 numbers rather than a function of . Write , and . Since , we have . Dividing by gives
With known , multiply each source posterior by and renormalize to obtain the target Bayes classifier without retraining, by the Bayes decision rule for the new priors. With two classes, add to the logit, as in the prior correction in the first figure. The challenge is estimating with unlabeled target data.
BBSE and identifiability from a confusion matrix
Take any fixed classifier , even one with poor accuracy or calibration, and write . Since depends on only through and is unchanged, is also unchanged. The law of total probability gives
where is the target prediction distribution, estimated from unlabeled inputs. 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: on source validation, on the target, and . Lipton, Wang and Smola (2018) prove consistency in Proposition 2. If (A.3) holds with separation from singularity and is the smallest singular value of , their Theorem 3 gives with high probability
Confusing two classes makes small. Squared error scales as its inverse square. Noise comes from source validation () and the target sample (). 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 with fixed components, the log likelihood of inputs is, up to constants independent of ,
EM alternates using the current priors to compute posteriors and averaging them for new priors . is concave in , 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.
The EM error falls like across the plot. The BBSE error flattens at large because of the 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.
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 . The gain appears at even though the error in is still large (0.20 in norm for BBSE). Decisions only change near boundaries, where the sign of the change matters. At , 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 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 and resample each class from a partition the classifier has not seen. This preserves .
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 with about half the error of BBSE (0.094 versus 0.181 in 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 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 and . They write for disagreement between two functions under marginal , giving .
Their Theorem 1 uses total variation to give . In general 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
and , so contributes one candidate to the supremum defining .
∎The first inequality follows from three uses of triangle inequality and Lemma 3, through . The guided proof develops it step by step. The finite-sample version replaces by its empirical estimate using uniform convergence from Lemma 1 and the VC dimension bound of at most .
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. 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, depends on , 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 is symmetric under complementation. Label each example in as 0 and each in as 1. A classifier calling set target has balanced error . Minimizing over gives
A chance discriminator () gives distance 0. A perfect discriminator () gives the maximum 2. In practice this is called the proxy distance . In Section 7 the authors note that a trained linear classifier gives a lower bound on because it may miss the best discriminator, and that quantity is itself below . The error guarantee needs an upper bound, which is computationally hard for half-spaces. A proxy alone does not certify the guarantee.
The bound is loose. Initially with target center , term 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 and . The final readout shows that their discrepancy is much lower than the supremum over pairs. Also, is sizable even without shift, since a half-space cannot fit the parabola. Finally, with the wider target and coincident centers, the best half-space detects less discrepancy than two lines around the source center. The measured discrepancy depends on discriminator capacity.
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 up to sampling noise. For Gaussians with equal covariance, a half-space maximizes . Under scale shift, the best half-space with appropriate captures only or 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 . Quadratic features recover total variation in this experiment.
What representation alignment can miss
The bound suggests learning a representation with indistinguishable source and target marginals and fitting a classifier on 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 learns features that reduce its ability to do so. The representation can also change the bound’s third term .
Zhao, Tachet des Combes, Zhang and Gordon (2019) give a simple counterexample in Section 4.1. Source has , and target has . Interval hypothesis classifies both perfectly, giving among interval hypotheses. The representation for and for maps both to , yielding perfect marginal alignment. But in labels reverse, with and . Every on therefore satisfies . 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 (), the sum of errors is at least . Stricter alignment can raise the lower bound. Under label shift the target marginal naturally differs from the source because the mixing proportions change.
Impossibility results
Without assumptions linking and , consider two worlds with identical source data and identical target inputs but opposite target labels and . An algorithm sees the same data in both and returns the same . Since , 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 ). With unlabeled targets alone, covariate shift and small divergence are insufficient without small . Small 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
- 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.
- 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.
- Under label shift, estimate with BBSE or EM, using EM only with calibrated probabilities. Correct posteriors by multiplying by , and monitor .
- Under covariate shift, estimate from a domain classifier. Check , consider clipping or flattening, and run weighted cross-validation. Reweighting can help under misspecification.
- Collect a few labeled target examples. They let you measure , 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 . With optimal , 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
Step 1 of 4. Which factorization of should you use?
Step 1 of 4. What is the first step?
bbse_weights(confusion_source, pred_dist_target). Input confusion_source is the joint source confusion matrix with C[i, j] = P_S(ŷ = i, y = j), and pred_dist_target is a length- vector with entries P_T(ŷ = i). Return the length- array w from 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))Summary
- Factor the joint distribution as or . 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 . A domain classifier estimates the ratio . Shimodaira’s analysis shows when a well-specified model needs no weighting.
- and . For , . Cortes, Mansour and Mohri’s bounds depend on . With , support overlap can still leave unbounded variance. Kish’s diagnostic can be optimistic, and clipping trades variance for bias.
- Under label shift, . BBSE solves with a classifier whose confusion matrix is invertible (error ). Maximum-likelihood EM requires calibration.
- . A domain discriminator estimates divergence (). A linear discriminator can underestimate it, and requires target labels.
- Zhao et al. show that with different label marginals, perfect alignment forces . Ben-David et al. show that with unlabeled targets, both small divergence and small matter.