AI Wiki中文/EN

Domain adaptation: when reweighting changes the right answer

领域适应

Fit a weighted constant classifier and expose two target worlds that identical unlabeled inputs cannot distinguish.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

The deployment population can change the best restricted model

A classifier trained where one input category is common may be deployed where that category is rare. Its source score measures performance on the old mixture, not automatically on the new one. Domain adaptation addresses a related prediction task across different source and target domains, using whatever target information the protocol permits.

Unsupervised domain adaptation has target inputs but no target training labels; supervised or semi-supervised variants have some target labels. Pan and Yang’s survey, Sections 2 and 4, distinguishes transfer settings and domain differences. Terminology varies, so state exactly which source/target data are available. Read importance sampling and generalization first.

Reweighting needs a stable conditional mechanism

One important special case is covariate shift:

PS(X)≠PT(X),PS(Y∣X)=PT(Y∣X).P_S(X)\ne P_T(X),\qquad P_S(Y\mid X)=P_T(Y\mid X).

The input distribution changes; the label distribution at a fixed input does not. With target support covered by the source and integrable loss, any fixed predictor h satisfies:

RT(h)=ET[ℓ(h(X),Y)]=ES ⁣[pT(X)pS(X)ℓ(h(X),Y)].R_T(h)=\mathbb E_T[\ell(h(X),Y)] =\mathbb E_S\!\left[\frac{p_T(X)}{p_S(X)}\ell(h(X),Y)\right].

Expand the source expectation as a sum over x,y. The ratio cancels p_S(x), and conditional equality replaces p_S(y|x) with p_T(y|x), leaving the target joint expectation. For continuous inputs, use densities and integration with the corresponding support conditions. Sugiyama, Krauledat and Müller, Sections 2.1–2.2, analyzes covariate shift and importance-weighted learning with known density ratios.

This motivates weighted empirical risk minimization:

h^=arg min⁡h∈H1n∑i=1nw(xi)ℓ(h(xi),yi),w(x)=pT(x)pS(x).\widehat h=\operatorname*{arg\,min}_{h\in\mathcal H} \frac1n\sum_{i=1}^n w(x_i)\ell(h(x_i),y_i),\qquad w(x)=\frac{p_T(x)}{p_S(x)}.

The fixed-predictor population identity is not a guarantee that the minimum training loss is an unbiased test estimate. Learning from the same data introduces selection effects; estimated ratios introduce further error. Validation must match the intended target risk.

A two-category example with a changed winner

Take source input probabilities(9/10,1/10), target probabilities(1/10,9/10), and positive-label probabilities η=(1/10,9/10) in both domains. A constant-zero classifier has source error 9/50 but target error 41/50. Constant one reverses those errors. The best constant model therefore changes.

Input weights are(1/9,9). Source counts[[81,9],[1,9]], with negative/positive columns, exactly reproduce the constructed source joint probabilities. Reweighting those 100 observations gives weighted positive mass 82 and total mass 100, so weighted constant fitting chooses class 1.

A richer predictor h(x)=x has error 1/10 in both domains. Under pure covariate shift, the pointwise Bayes classifier under the same classification loss is unchanged where conditionals agree. Reweighting can still matter for a restricted model family, regularization, finite data or evaluation. The constant-model example does not claim that every optimal classifier must change.

Separate fitting information from target truth

The complete Python 3.12 program fits constant labels from grouped source counts and target input proportions. Target labels are not passed to the fitting function. A separate audit computes risks in two hypothetical target worlds so that the assumptions can be checked exactly.

from fractions import Fraction as F


def probability(values, positive=False):
    values=list(values)
    if not 1<=len(values)<=8 or any(type(v) not in (int,F) or not 0<=v<=1 or (positive and v==0) for v in values) or sum(values,F(0))!=1:
        raise ValueError('one to eight normalized rational probabilities required')
    return list(map(F,values))


def audit(source_x, target_x, eta_source, candidates, eta_target=None):
    ps=probability(source_x,True);pt=probability(target_x);n=len(ps)
    es=list(eta_source);et=list(es if eta_target is None else eta_target);candidates=[list(h) for h in candidates]
    if len(pt)!=n or len(es)!=n or len(et)!=n or any(type(v) not in (int,F) or not 0<=v<=1 for v in es+et):
        raise ValueError('matching rational conditional positive-label probabilities required')
    if not 1<=len(candidates)<=8 or any(len(h)!=n or any(type(v) is not int or v not in (0,1) for v in h) for h in candidates):
        raise ValueError('bounded binary candidate predictions required')
    ratios=[t/s for s,t in zip(ps,pt)];rows=[]
    for h in candidates:
        source_errors=[F(v) if pred==0 else 1-F(v) for v,pred in zip(es,h)]
        target_errors=[F(v) if pred==0 else 1-F(v) for v,pred in zip(et,h)]
        source=sum(p*e for p,e in zip(ps,source_errors))
        weighted=sum(p*w*e for p,w,e in zip(ps,ratios,source_errors))
        target=sum(p*e for p,e in zip(pt,target_errors));rows.append((source,weighted,target))
    return ratios,rows


def fit_constant(counts, target_x):
    counts=[list(row) for row in counts]
    if not 1<=len(counts)<=8 or any(len(row)!=2 or any(type(v) is not int or not 0<=v<=100000 for v in row) or sum(row)==0 for row in counts):
        raise ValueError('nonempty negative/positive count pairs required for each source category')
    total=sum(map(sum,counts));ps=[F(sum(row),total) for row in counts];eta=[F(row[1],sum(row)) for row in counts]
    ratios,rows=audit(ps,target_x,eta,[[0]*len(ps),[1]*len(ps)])
    source_best=min(range(2),key=lambda i:(rows[i][0],i))
    weighted_best=min(range(2),key=lambda i:(rows[i][1],i))
    return source_best,weighted_best,ps,eta,ratios


if __name__=='__main__':
    target_x=[F(1,10),F(9,10)];counts=[[81,9],[1,9]]
    separate,adapted,ps,eta,ratios=fit_constant(counts,target_x)
    print('unweighted/weighted constant labels:',separate,adapted)
    print('input importance ratios:',*[str(v) for v in ratios])
    candidates=[[0,0],[1,1],[0,1]]
    for name,target_eta in [('unchanged label mechanism',eta),('flipped label mechanism',[1-v for v in eta])]:
        _,rows=audit(ps,target_x,eta,candidates,target_eta)
        print(name,'(source, weighted source, actual target risk)')
        for h,row in zip(candidates,rows):print(h,*map(str,row))

Output:

unweighted/weighted constant labels: 0 1
input importance ratios: 1/9 9
unchanged label mechanism (source, weighted source, actual target risk)
[0, 0] 9/50 41/50 41/50
[1, 1] 41/50 9/50 9/50
[0, 1] 1/10 1/10 1/10
flipped label mechanism (source, weighted source, actual target risk)
[0, 0] 9/50 41/50 9/50
[1, 1] 41/50 9/50 41/50
[0, 1] 1/10 1/10 9/10

The code supports up to eight categorical inputs and eight candidate classifiers, using exact fractions. It requires every source category to have positive probability, a convenient stronger contract than only covering target support. Ties in constant fitting choose class 0. Risk evaluation takes O(Km) rational operations for K candidates and m categories, plus bit costs.

The grouped counts were constructed to equal the stipulated source distribution. This is why empirical and population calculations agree here; it is not a claim that estimated density ratios from arbitrary samples are exact. The audit’s target conditional probabilities are simulation truth, unavailable to the unsupervised fitter.

Matching input distributions cannot identify changed labels

In the second world, keep the same source data and target input probabilities but flip target conditionals to(9/10,1/10). All input weights and weighted-source risks remain unchanged. The selected constant-one model now has actual target error 41/50 instead of 9/50. The apparently strong h(x)=x model has actual target error 9/10 instead of its weighted-source estimate 1/10.

Both target worlds present identical unlabeled inputs. An algorithm seeing only these source labels and target inputs cannot determine which label mechanism holds without additional assumptions or target information. This explicit ambiguity explains why marginal alignment alone cannot certify target accuracy.

Weighting also becomes unstable when target-important regions are rare in source data. No weight can supply labels where the source has zero support. Clipping or smoothing ratios changes the bias/variance tradeoff and must be stated. The IWCV paper, Section 2.2, distinguishes consistency arguments from finite-sample stability.

Label shift instead assumes stable input distributions conditional on the label while label priors change. Conditional or concept shift changes the label mechanism itself. These are different models, not names for one correction. Representation alignment, pseudo-labeling and adversarial adaptation require their own assumptions; collapsing inputs can make domains look alike while deleting label information.

Which part of the distribution changed?

  1. What are the importance ratios in the two-category example?

Answer 1: 1/9 and 9, target input probability divided by source input probability.

  1. Why does constant-zero fitting look good on the source but bad on the first target world?

Answer 2: The category mixture reverses, changing its error from 9/50 to 41/50.

  1. What is unchanged in the two target worlds shown by the audit?

Answer 3: Source labeled data and target input proportions; only the unseen target label mechanism changes.

  1. Does pure covariate shift necessarily change the unrestricted Bayes classifier?

Answer 4: No. Under unchanged conditionals and the same loss, its pointwise decision remains the same; restricted models can have a different best fit.

Audit the adaptation assumption before optimizing it

Project: vary target input proportions and repeat the risk table. Then interpolate between the original and flipped target label mechanisms. Record the gap between weighted-source risk and actual target risk. If collecting a small target audit sample, keep it separate from adaptation and threshold tuning.

In a larger experiment, compare source-only training, weighting, representation adaptation and any permitted target-supervised baseline with the same target protocol. Report support overlap, ratio estimation, per-domain metrics and uncertainty. Transfer learning provides the broader reuse setting; this chapter supplies explicit distribution assumptions that a successful adaptation claim must survive.

Make a prediction, then check

Why can input weighting fail in the second target world?

Choose one answer

Learning objectives

  • Derive the target-risk identity under covariate shift.
  • Fit a weighted model while keeping target labels unavailable.
  • Construct a conditional-shift counterexample to marginal alignment.

Prerequisites & connections

Explore related knowledge →

References

  1. Covariate Shift Adaptation by Importance Weighted Cross Validation
    Masashi Sugiyama; Matthias Krauledat; Klaus-Robert Müller · 2007
  2. A Survey on Transfer Learning — accepted author manuscript
    Sinno Jialin Pan; Qiang Yang

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-06 · Codex single-agent authored technical review: cited primary-source scope, explicit assumptions, original calculations and counterexamples, runnable tests and bilingual review; not independent human or second-agent review.

  • Single-agent authored technical review: bounded primary-source locations, assumptions, original derivations, exact/literal references and matching bilingual equations/examples/exercises. Not independent human or second-agent review.
  • Four focused CPython3.12.4 tests passed per chapter. Exact rational metrics, four-outcome task risks, source/frozen/gradient fits and shifted-domain risks are checked against literal or analytic references. No external runtime dependencies.
  • Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
  • Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.