Search

Search papers and lessons

Domain-Adversarial Training of Neural Networks

Yaroslav Ganin, Evgeniya Ustinova, Hana Ajakan et al. · 2015

Ganin and coauthors (2015) train a network to classify labelled source data while a built-in adversary tries to tell source from target, so the features that survive are useful for both.

On this page

  • Colour = topic mix
  • Probability
  • Calculus
  • Discrete math
  • Neural network basics
  • Linear algebra
  • Learning basics
  • ReadReady to readNot yet

TL;DR

Ganin and coauthors show how to train a neural network on labelled examples from one data source, called the source domain, while also using unlabelled examples from a different source, the target domain. The network has two heads: one predicts the label, and one tries to guess which domain an example came from. A single layer between the shared features and the domain head flips the sign of the gradient, so the features are trained to make the domain guess fail while still predicting the label well. The result is a model that works on the target domain without any target labels, and that can be built and trained with ordinary backpropagation.

Builds on: Domain Adaptation, Backpropagation, Minimax Game · Leads to: Gradient Reversal Layer, and the wider family of methods that learn domain-invariant features

Why it mattered

The idea that a model should be trained to ignore where its data came from, rather than being fixed up afterwards, became a standard tool in Domain Adaptation. The paper's method needs no special solver: it is an ordinary feed-forward network with one extra layer, trained with Stochastic Gradient Descent in any deep learning library. That made it cheap to try on existing architectures, and it was applied to sentiment analysis, digit and traffic-sign recognition, object recognition and person re-identification in the same paper. The paper also gave a concrete way to turn a theoretical bound on the target error into a training objective, which is part of why it was cited so widely.

The problem

Labels are expensive, and a model trained on one collection often fails on another. Training a classifier on synthetic images is cheap because the labels come for free, but real photographs look different, so the model's accuracy drops on them. Sentiment models trained on book reviews often do worse on kitchen-appliance reviews. This shift between training and test distributions is called Covariate Shift when only the inputs change, and Domain Adaptation is the general task of coping with it.

Before this paper, many methods fixed a feature representation first and then adapted a classifier on top, or matched feature distributions with a separate procedure. Theory from Ben-David and coauthors suggested a better target: find a representation in which an algorithm cannot tell the source examples from the target examples, and in which the source labels can still be predicted. The open question was how to get such a representation from a deep network trained with gradient methods.

How it works

The walkthrough below follows one training step. The network has three parts: a feature extractor GfG_f that maps an input to a vector of features, a label predictor GyG_y that maps features to class probabilities, and a domain classifier GdG_d that maps features to the probability that the input came from the target domain.

  1. Pick a batch. Take 128 examples, half from the labelled source domain and half from the unlabelled target domain. Each source example carries its label, and each target example carries only a domain tag.
  2. Run the label head on source examples. Pass a source example through GfG_f and then GyG_y. Compare the predicted probabilities with the true label using a loss. This loss is what pushes the network to classify the source domain well. Check: the loss is small when the true label gets high probability and large when it gets low probability.
  3. Run the domain head on all examples. Pass every example, source and target, through GfG_f and then GdG_d. The domain loss is small when GdG_d guesses the true domain tag. Check: both domains contribute to this loss, which is why it can be computed without any target labels.
  4. Send gradients backward. Run backpropagation from both losses. Across the gradient reversal layer, the gradient coming from the domain loss is multiplied by a negative number, so the feature extractor receives the opposite of the gradient that would help the domain head.
  5. Work the numbers for one feature. Suppose the domain loss would send the feature f1f_1 a gradient of +0.4. With the trade-off weight λ\lambda set to 1, the reversal turns it into −0.4. Gradient descent steps against the received gradient, so with learning rate 0.01 the feature moves by −0.01×(−0.4)=+0.004-0.01 \times (-0.4) = +0.004. That step makes the domain loss larger, so the feature becomes harder for the domain head to use. Check: the feature moved in the direction that hurts domain classification, which is the goal.
  6. Update the domain head normally. The domain classifier's own weights still follow their ordinary gradient, so the domain head keeps trying to get better at its job. The two heads therefore compete while the features are shaped by the reversed signal.
flowchart LR
  X["input x"] --> F["feature extractor G_f"]
  F --> Y["label predictor G_y"]
  F --> R["gradient reversal layer"]
  R --> D["domain classifier G_d"]
  Y --> LY["label loss, source examples only"]
  D --> LD["domain loss, source and target"]

Once training ends, only GfG_f and GyG_y are used. The domain head is discarded, and the label predictor is applied to target inputs.

The math

Write SS for the labelled source sample of nn examples and TT for the unlabelled target sample of n′n' examples, with N=n+n′N = n + n'. Each example gets a domain tag did_i, equal to 0 for source and 1 for target. The label loss Ly\mathcal{L}_y is cross-entropy on the predicted class probabilities, and the domain loss Ld\mathcal{L}_d is the binary cross-entropy on the predicted domain probability.

Step 1 in symbols: the two heads

The feature extractor Gf(⋅;θf)G_f(\cdot; \theta_f) has parameters θf\theta_f. The label predictor Gy(⋅;θy)G_y(\cdot; \theta_y) outputs one probability per class, and the domain classifier Gd(⋅;θd)G_d(\cdot; \theta_d) outputs one probability that the input came from the target domain. The per-example losses are

Lyi(θf,θy)=Ly(Gy(Gf(xi;θf);θy),yi),Ldi(θf,θd)=Ld(Gd(Gf(xi;θf);θd),di).\mathcal{L}_y^i(\theta_f, \theta_y) = \mathcal{L}_y\big(G_y(G_f(\mathbf{x}_i; \theta_f); \theta_y), y_i\big), \qquad \mathcal{L}_d^i(\theta_f, \theta_d) = \mathcal{L}_d\big(G_d(G_f(\mathbf{x}_i; \theta_f); \theta_d), d_i\big).

Step 2 in symbols: the trade-off objective

The paper combines the two losses into one objective with a trade-off weight λ\lambda:

E(θf,θy,θd)=1n∑i=1nLyi(θf,θy)−λ(1n∑i=1nLdi(θf,θd)+1n′∑i=n+1NLdi(θf,θd)).E(\theta_f, \theta_y, \theta_d) = \frac{1}{n}\sum_{i=1}^{n} \mathcal{L}_y^i(\theta_f, \theta_y) - \lambda \left( \frac{1}{n}\sum_{i=1}^{n} \mathcal{L}_d^i(\theta_f, \theta_d) + \frac{1}{n'}\sum_{i=n+1}^{N} \mathcal{L}_d^i(\theta_f, \theta_d) \right).

The label loss is averaged over source examples, and the domain loss is averaged over the source and the target separately, then added. The minus sign is the heart of the method: the features are chosen to make EE small on the label part and large on the domain part. The paper looks for a saddle point, where θf\theta_f and θy\theta_y minimise EE and θd\theta_d maximises it:

(θ^f,θ^y)=arg⁡min⁡θf,θyE(θf,θy,θ^d),θ^d=arg⁡max⁡θdE(θ^f,θ^y,θd).(\hat\theta_f, \hat\theta_y) = \arg\min_{\theta_f, \theta_y} E(\theta_f, \theta_y, \hat\theta_d), \qquad \hat\theta_d = \arg\max_{\theta_d} E(\hat\theta_f, \hat\theta_y, \theta_d).

Step 3 in symbols: the update rules

For one example, the stochastic updates with learning rate μ\mu are

θf←θf−μ(∂Lyi∂θf−λ∂Ldi∂θf),θy←θy−μ∂Lyi∂θy,θd←θd−μλ∂Ldi∂θd.\theta_f \leftarrow \theta_f - \mu\left(\frac{\partial \mathcal{L}_y^i}{\partial \theta_f} - \lambda\frac{\partial \mathcal{L}_d^i}{\partial \theta_f}\right), \qquad \theta_y \leftarrow \theta_y - \mu\frac{\partial \mathcal{L}_y^i}{\partial \theta_y}, \qquad \theta_d \leftarrow \theta_d - \mu\lambda\frac{\partial \mathcal{L}_d^i}{\partial \theta_d}.

The only unusual line is the first. The feature extractor subtracts the domain gradient, where ordinary training would add it. Adding it would instead train the features to help the domain head tell the domains apart, the opposite of what is wanted.

Step 4 in symbols: the gradient reversal layer

The gradient reversal layer R\mathcal{R} is a pseudo-function with two parts: on the forward pass it is the identity, and on the backward pass its derivative is minus the identity,

R(x)=x,dRdx=−I.\mathcal{R}(\mathbf{x}) = \mathbf{x}, \qquad \frac{d\mathcal{R}}{d\mathbf{x}} = -\mathbf{I}.

Placing R\mathcal{R} between GfG_f and GdG_d makes ordinary gradient descent on the modified objective produce the updates of Step 3. The paper's Equation 18 writes the full objective with R\mathcal{R} inside, and the model can then be trained with the usual Gradient Descent machinery.

Step 5 in symbols: why it targets the domain gap

The paper builds on a bound due to Ben-David and coauthors. For a hypothesis class H\mathcal{H} of classifiers, the empirical H\mathcal{H}-divergence between the source and target samples measures how well the best classifier in the class can tell them apart, and the paper's regulariser RR is the best value, over the domain head's parameters, of a negative domain loss, so that 2(1−R)2(1 - R) serves as a surrogate for the empirical divergence. Their theorem bounds the target risk RT(η)R_T(\eta) of any classifier η\eta by

RT(η)≤RS(η)+d^H(S,T)+(complexity terms that depend on the VC dimension and sample sizes)+β,R_T(\eta) \le R_S(\eta) + \hat{d}_{\mathcal{H}}(S, T) + \text{(complexity terms that depend on the VC dimension and sample sizes)} + \beta,

where RSR_S is the source risk and β\beta is the error of the best classifier that works on both domains. Making the features hard to separate by domain shrinks the middle term, and the source risk term is kept small by the label loss.

Results

Amazon reviews, sentiment. The paper uses the Amazon reviews benchmark with four product domains (books, dvd, electronics and kitchen), and each text is encoded as a 5,000-dimensional feature vector of unigrams and bigrams. There are twelve source-target pairs, with 2,000 labelled source examples and 2,000 unlabelled target examples per task. On the original features, DANN's accuracy is higher than the plain network's on several pairs. For example, from dvd to electronics it scores .754 against .732 for the network and .748 for the linear SVM. The paper reports that DANN is significantly better than the network and the SVM, with probabilities 0.87 and 0.83 under a Poisson binomial test. When DANN is applied on top of marginalised denoising autoencoder features, the probabilities rise to 0.92 and 0.88. On the dvd-to-electronics pair with those features, DANN gets .809 against .768 for the network and .739 for the SVM.

Toy problem. Two interleaved moons are the source, and the target is a copy rotated by 35 degrees with its labels removed. A plain network with 15 hidden neurons draws a boundary that does not match the target. DANN, with the same architecture and a trade-off of 6, draws a boundary that classifies both source and target points, and its hidden representation spreads target points among source points instead of leaving them in clusters with no source points.

Images. For MNIST to MNIST-M, the source is handwritten digits and the target is the same digits blended onto colour photo patches. The source-only model does poorly, and the adapted model improves on it. For synthetic digits to SVHN street-view house numbers, the adapted model closes almost 80 percent of the gap between training on source data alone and training on target data with labels. The reverse direction, MNIST to SVHN, is a failure case: the non-adapted model reaches about 0.25 accuracy and the method does not improve on it. The Office benchmark has 2,817 labelled images in its largest domain, and on the Amazon to Webcam transfer the paper reports a very considerable gain over the previous state of the art.

Person re-identification. The descriptor version improves cross-dataset matching on PRID, VIPeR and CUHK, and the paper reports a considerable gain when PRID is involved, since it differs most from the other sets.

Limits. The shallow experiments use a reverse validation procedure to choose hyperparameters without target labels, but the deep experiments use fixed schedules instead of a grid search. The authors also note slight overfitting late in training, where target accuracy degrades while source accuracy keeps improving. The semi-supervised extension is only sketched, and the authors leave a thorough test to future work.

Reading guide

Read the paper in this order, with the lessons each part depends on.

Check yourself

QuestionIn plain words, what does the domain head try to do, and what does the feature extractor try to do to it?Show answer

The domain head tries to predict, for each input, whether it came from the source or the target domain. The feature extractor is trained so that the domain head fails at this, which happens when the features carry no information about the domain. Through the gradient reversal layer, the feature extractor's update moves against the domain head's gradient, so the two push in opposite directions.

QuestionWith a learning rate of 0.01, a trade-off weight of 1, and a domain-loss gradient of +0.4 on a feature, how far does that feature move in one update, and in which direction?Show answer

The reversed gradient is −0.4. The update subtracts the received gradient, so the feature changes by −0.01 times −0.4, which is +0.004. It moves up by 0.004, the direction that makes the domain loss larger.

QuestionWhy does the paper subtract the domain gradient in its update for the feature extractor, rather than adding it as ordinary gradient descent on a summed loss would?Show answer

Adding the domain gradient would make the features easier for the domain head to separate, which lowers the domain loss, so the features would become more domain specific. Subtracting it makes the feature extractor maximise the domain loss, which is what makes the features domain invariant.

QuestionA team wants to adapt a sentiment model from movie reviews to book reviews and has no book labels. Which parts of the DANN setup would they need, and what would they monitor to see whether the method is helping?Show answer

They need labelled movie reviews as the source, unlabelled book reviews as the target, a shared feature extractor with a label head and a domain head, and a gradient reversal layer between the features and the domain head. They would monitor the label loss on the source and the domain loss, and they would also check the target predictions against whatever held-out evidence they have, since the target has no labels in training. A domain loss that stays near its chance value, with the label loss still falling, is the pattern the method aims for.

Sources

Read the full paper

Yaroslav Ganin, Evgeniya Ustinova, Hana Ajakan et al., 2015. arXiv:1505.07818