AI Logic

Domain Adaptation

ADDA

Updated:

The three stages of ADDA training. Left: pretraining, in which the source CNN and classifier are trained on source images. Center: adversarial adaptation, in which a discriminator distinguishes features of the frozen source CNN from those of the target CNN. Right: inference, in which target images are classified with the target CNN and the pretrained classifier

Background and overview

ADDA (Adversarial Discriminative Domain Adaptation) is a domain adaptation method that keeps the feature extractor trained on the source frozen, trains a separate target feature extractor with the same loss as a GAN, and maps target images into the same feature space as the source. It was proposed by Tzeng et al. in 2017.

A model trained on labeled data (the source) loses accuracy on unlabeled data of a different nature (the target) because of differences in appearance (domain shift). To address this, "adversarial" methods have been proposed that learn features to fool a discriminator that distinguishes domains. The representative one is DANN.

The ADDA paper first organized adversarial domain adaptation methods as combinations of three choices.

ChoiceOptionsDANN (gradient reversal)ADDA
Base modelProduce images (generative) or produce features (discriminative)DiscriminativeDiscriminative
Weight sharingShared or separate between source and targetSharedSeparate
Adversarial lossMinimax, confusion, or GAN lossMinimaxGAN

Within this framework, ADDA is the previously untried combination of a "discriminative model, unshared weights, and GAN loss." The paper argues that because it does not use an image-generating model, the setup is simple, and because it has a separate target feature extractor, it can align source and target more easily even when their appearance differs greatly.

The three training stages and losses

As in Figure 3 of the paper, ADDA trains and infers in three stages. The notation is source images XsX_s with labels YsY_s, target images XtX_t, the source feature extractor (CNN) MsM_s, the target feature extractor MtM_t, the classifier CC, and the discriminator DD.

  1. Pretrain on the source: Train MsM_s and CC on source images and labels with an ordinary classification loss.
  2. Adversarial adaptation: Freeze MsM_s and train MtM_t, initialized with the weights of MsM_s. The discriminator DD learns to tell whether a feature came from the source (Ms(xs)M_s(x_s)) or the target (Mt(xt)M_t(x_t)), and MtM_t learns to make DD think it "came from the source." These two are repeated alternately.
  3. Inference on the target: Map target images to features with MtM_t and classify them with the classifier CC trained in stage 1.

The classification loss in stage 1 is cross-entropy (KK is the number of classes).

min⁡Ms,C  Lcls=−E(xs,ys)∼(Xs,Ys)∑k=1K1[k=ys]log⁡C(Ms(xs))\min_{M_s, C} \; \mathcal{L}_{\mathrm{cls}} = -\mathbb{E}_{(x_s, y_s) \sim (X_s, Y_s)} \sum_{k=1}^{K} \mathbb{1}_{[k = y_s]} \log C(M_s(x_s))

The loss of the discriminator DD in stage 2 is a two-class cross-entropy with source as 1 and target as 0 (Eq. (2)).

min⁡D  LadvD=−Exs∼Xs[log⁡D(Ms(xs))]−Ext∼Xt[log⁡(1−D(Mt(xt)))]\min_{D} \; \mathcal{L}_{\mathrm{adv}_D} = -\mathbb{E}_{x_s \sim X_s}[\log D(M_s(x_s))] - \mathbb{E}_{x_t \sim X_t}[\log(1 - D(M_t(x_t)))]

The loss of MtM_t is the GAN loss with inverted labels (Eq. (7)). It trains toward having target features judged as "source (1)."

min⁡Mt  LadvM=−Ext∼Xt[log⁡D(Mt(xt))]\min_{M_t} \; \mathcal{L}_{\mathrm{adv}_M} = -\mathbb{E}_{x_t \sim X_t}[\log D(M_t(x_t))]

Because the source side MsM_s stays fixed and only the target side MtM_t moves to align, this takes the same form as a GAN, in which "the distribution of real images does not change, and only the distribution produced by the generator is moved closer."

The reason for choosing the GAN loss is gradient strength. If the discriminator's loss is simply maximized (LadvM=−LadvD\mathcal{L}_{\mathrm{adv}_M} = -\mathcal{L}_{\mathrm{adv}_D}, the same as DANN's gradient reversal), the gradient to the feature extractor vanishes when the discriminator quickly learns to tell them apart early in training. The inverted-label loss keeps the same optimum while returning strong gradients to the target feature extractor.

Why separate the weights

Many earlier methods, including DANN, shared one feature extractor between source and target. Sharing has the advantages of fewer parameters and features that can distinguish classes at least on the source. On the other hand, a single network must handle images from two domains that look different, which can make optimization harder.

By having a separate target feature extractor MtM_t, ADDA can learn low-level features specific to the target (color, texture, image quality, and so on) separately from the source. As an analogy, to read documents in a foreign language, one keeps native-language reading comprehension (CC) as is and trains only a new "translator" (MtM_t) from the foreign language into the native one.

However, since the target has no labels, separating the weights risks MtM_t collapsing into features that cannot distinguish classes. ADDA prevents this in two ways.

  • MtM_t is initialized with the weights of the trained MsM_s.
  • During adaptation, MsM_s is frozen and only the target side moves.

Because the source feature space does not move, MtM_t only aligns toward the source space, and the classifier CC learned in stage 1 can be used as is.

Training setup and results

The paper first evaluates on pairs of digit image datasets.

  • Between MNIST and USPS (handwritten digits), 2,000 images are sampled from MNIST and 1,800 from USPS. From SVHN (digits in house-number photos) to MNIST, all training data is used.
  • The feature extractor is a slightly modified version of the LeNet model that ships with Caffe.
  • The discriminator is a 3-layer fully connected network: two 500-unit layers (ReLU) followed by an output layer.

The accuracy evaluated on the unlabeled target is as follows (Table 2 of the paper).

MethodMNIST → USPSUSPS → MNISTSVHN → MNIST
Source only0.7520.5710.601
Gradient reversal (DANN)0.7710.7300.739
Domain confusion0.7910.6650.681
CoGAN0.9120.891Did not converge
ADDA0.8940.9010.760

Between MNIST and USPS, it achieves about the same accuracy as CoGAN, which generates images with two GANs, with a much simpler setup. On SVHN → MNIST, where the appearance gap is large, CoGAN failed to converge, whereas ADDA had the highest accuracy among the compared methods.

The paper also evaluates adaptation across different sensing modalities, from color (RGB) images to depth images. Objects of 19 classes were cropped from the NYU Depth dataset, with 2,186 labeled RGB images as the source and 2,401 unlabeled depth images as the target. Using VGG-16 pretrained on ImageNet, mean per-class accuracy rose from 13.9% when trained on the source only to 21.1% (46.8% when trained with target labels).

Practical considerations

Because the separate MtM_t is trained without target labels, mistakes in initialization or training procedure can make it collapse into features that cannot distinguish classes (Chapter 4 of the paper). Always initialize MtM_t with the trained MsM_s, and freeze MsM_s and the classifier CC during adaptation. Since this is adversarial training, also watch the balance of strength between the discriminator and MtM_t.

  • Not every class improves. In the NYU Depth experiment, the mean improved, but three classes that had no correct predictions before adaptation did not improve, and two classes, pillow and night stand, decreased in accuracy.
  • What gets aligned is the overall feature distribution. The discriminator only distinguishes source from target, so there is no guarantee that per-class distributions align. When class proportions differ greatly between source and target, aligning the whole can instead shift class boundaries.
  • Training is split into two stages. Source pretraining and adversarial adaptation run in sequence, so there are more steps than with methods such as DANN that need a single training run. In exchange, the classification loss does not need to be revisited during adaptation.

Comparison with other domain adaptation methods

Deep domain adaptation methods can be compared by "what about the two domains' features is aligned, and how."

MethodWhat is alignedHowFeature extractor
DDCFeature distribution of one layerAdds MMD (the difference of the two distributions' means) to the lossShared between the two domains
DANFeature distributions of multiple layersAdds MMD with multiple kernels to the lossShared
Deep CORALSecond-order statistics of features (covariance)Adds the covariance difference to the lossShared
DANNFeature distributionAdversarial training with a domain discriminator and a gradient reversal layerShared
ADDAFeature distributionAdversarial training with the same loss as a GAN. The extractor trained on the source is frozen, and a separate target extractor is trainedSeparate per domain

Methods that "add a distance to the loss," such as DDC, DAN, and Deep CORAL, tend to train stably, but only the chosen statistics are aligned. DANN and ADDA try to reduce every difference the discriminator can detect. DANN gets by with one feature extractor and a single training run, while ADDA has a dedicated target feature extractor, which suits cases where source and target look very different (SVHN → MNIST and RGB → depth in the paper).

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.utils.data import DataLoader

"""
ADDA from MNIST (source, labeled) to USPS (target, unlabeled).
USPS labels are used only for evaluation. The optimizer settings are examples (not given for the paper's digit experiments)
"""

batch_size = 128
device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'

transform = transforms.Compose([
  transforms.Resize(28),  # USPS is 16x16, so match MNIST
  transforms.ToTensor(),
  transforms.Normalize((0.5,), (0.5,)),
])
source = datasets.MNIST(root='./data', train=True, download=True, transform=transform)
target = datasets.USPS(root='./data', train=True, download=True, transform=transform)
target_test = datasets.USPS(root='./data', train=False, download=True, transform=transform)
source_loader = DataLoader(source, batch_size=batch_size, shuffle=True, drop_last=True)
target_loader = DataLoader(target, batch_size=batch_size, shuffle=True, drop_last=True)
test_loader = DataLoader(target_test, batch_size=256)


def make_encoder():  # LeNet-style feature extractor M
  return nn.Sequential(
    nn.Conv2d(1, 20, 5), nn.MaxPool2d(2), nn.ReLU(),
    nn.Conv2d(20, 50, 5), nn.MaxPool2d(2), nn.ReLU(),
    nn.Flatten(), nn.Linear(50 * 4 * 4, 500), nn.ReLU(),
  )


src_encoder = make_encoder().to(device)        # M_s
classifier = nn.Linear(500, 10).to(device)     # C
discriminator = nn.Sequential(                 # D: 2 layers of 500 units (ReLU) + output (paper's setting)
  nn.Linear(500, 500), nn.ReLU(),
  nn.Linear(500, 500), nn.ReLU(),
  nn.Linear(500, 1),                           # source (1) or target (0)
).to(device)

# (1) Pretrain on source: train M_s and C with the classification loss
opt = optim.Adam(list(src_encoder.parameters()) + list(classifier.parameters()), lr=1e-3)
for epoch in range(10):
  for xs, ys in source_loader:
    xs, ys = xs.to(device), ys.to(device)
    loss = F.cross_entropy(classifier(src_encoder(xs)), ys)
    opt.zero_grad()
    loss.backward()
    opt.step()

# (2) Adversarial adaptation: initialize M_t with M_s, and freeze M_s and C
tgt_encoder = make_encoder().to(device)
tgt_encoder.load_state_dict(src_encoder.state_dict())
for p in list(src_encoder.parameters()) + list(classifier.parameters()):
  p.requires_grad = False

opt_d = optim.Adam(discriminator.parameters(), lr=2e-4, betas=(0.5, 0.999))
opt_t = optim.Adam(tgt_encoder.parameters(), lr=2e-4, betas=(0.5, 0.999))
for epoch in range(20):
  for (xs, _), (xt, _) in zip(source_loader, target_loader):
    xs, xt = xs.to(device), xt.to(device)

    # Discriminator D: predict 1 for source features and 0 for target features (L_advD)
    with torch.no_grad():
      fs, ft = src_encoder(xs), tgt_encoder(xt)
    logits = discriminator(torch.cat([fs, ft])).squeeze(1)
    labels = torch.cat([torch.ones(len(fs)), torch.zeros(len(ft))]).to(device)
    loss_d = F.binary_cross_entropy_with_logits(logits, labels)
    opt_d.zero_grad()
    loss_d.backward()
    opt_d.step()

    # Target feature extractor M_t: flip the labels so the target is judged as 1 (L_advM, GAN loss)
    logits_t = discriminator(tgt_encoder(xt)).squeeze(1)
    loss_t = F.binary_cross_entropy_with_logits(logits_t, torch.ones(len(xt), device=device))
    opt_t.zero_grad()
    loss_t.backward()
    opt_t.step()

# (3) Inference on target: map with M_t and classify with classifier C from (1)
tgt_encoder.eval()
classifier.eval()
correct = total = 0
with torch.no_grad():
  for images, labels in test_loader:
    images, labels = images.to(device), labels.to(device)
    predicted = classifier(tgt_encoder(images)).argmax(dim=1)
    total += labels.size(0)
    correct += (predicted == labels).sum().item()

print(f"Target Accuracy: {100 * correct / total:.2f}%")

FAQ

Q. What is the difference between ADDA and DANN?
A.

There are two main differences. One is weight sharing: DANN shares one feature extractor between source and target, whereas ADDA has a separate target feature extractor MtM_t. The other is the feature extractor's loss: DANN directly maximizes the discriminator's loss with a gradient reversal layer (LadvM=−LadvD\mathcal{L}_{\mathrm{adv}_M} = -\mathcal{L}_{\mathrm{adv}_D}), whereas ADDA uses the GAN loss with inverted labels. The training procedure also differs: DANN is a single run, while ADDA has two stages, pretraining and adaptation.

Q. Why use the same loss as a GAN when no images are generated?
A.

Because ADDA's MtM_t can be seen as "generating" features rather than images. Treating the fixed source feature distribution as "real" and the target feature distribution output by MtM_t as "generated," it takes the same form as a GAN generator moving toward the real distribution. The paper reasons that much of the machinery needed to generate images is unnecessary for adaptation aimed at classification, and chooses to train adversarially only in feature space.

Q. Is the source feature extractor used at inference time?
A.

No. Target images are mapped to features with the target feature extractor MtM_t trained during adaptation and classified with the classifier CC trained on the source. The source feature extractor MsM_s is used only for pretraining and for showing the discriminator "real" features during adaptation.

References

  1. Tzeng, E., Hoffman, J., Saenko, K., & Darrell, T. (2017). Adversarial Discriminative Domain Adaptation. Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR).
  2. Ganin, Y., & Lempitsky, V. (2015). Unsupervised Domain Adaptation by Backpropagation. Proceedings of the 32nd International Conference on Machine Learning (ICML), PMLR 37, 1180–1189.