AI Logic

Domain Adaptation

DAN

Updated:

The training flow of DAN. Left: source and target images pass through AlexNet's conv1-conv3 (frozen), conv4-conv5, fc6, fc7, and classifier fc8, with MK-MMD computed at each of fc6-fc8. Right: a graph of Gaussian kernels with different widths, and the additions and subtractions used to estimate MK-MMD from a quadruple of two source points and two target points

Background and overview

DAN (Deep Adaptation Network) is a domain adaptation method that makes a CNN trained on labeled data (the source) usable on unlabeled data of a different nature (the target). It was proposed by Long et al. in 2015. At multiple later layers of the CNN, it measures the difference between source and target feature distributions with MMD combining multiple kernels (MK-MMD), and minimizes it by adding it to the classification loss.

In deep learning, layers closer to the network input are known to learn "general features that apply to any data," while layers closer to the output learn "features specialized to the original data and task." The DAN paper starts from this finding (from the work of Yosinski et al.) that "features in layers close to the output are hard to transfer to another domain."

The earlier DDC minimized the difference between the two domains' means for the features of one layer. DAN extends this in two directions.

  • More layers aligned: It aligns the two domains' distributions at all three fully connected layers fc6, fc7, and fc8 of AlexNet.
  • A stronger measure: With MK-MMD, which combines Gaussian kernels of different widths, it measures not only the mean but also differences in the shape of the distributions.

It also uses an unbiased estimate of MK-MMD whose computation scales linearly with the number of samples (linear time), so that it can be trained with minibatch stochastic gradient descent.

Network architecture and loss

As in Figure 1 of the paper, DAN's network is based on AlexNet pretrained on ImageNet. Source and target images pass through a network with the same weights.

  1. conv1-conv3: These are general features that apply to any data, so they are frozen at the pretrained weights.
  2. conv4-conv5: These begin to be slightly domain-biased, so they are fine-tuned.
  3. fc6, fc7: These layers are specialized to the original task, so they are fine-tuned while the source and target distributions are aligned with MK-MMD.
  4. fc8 (classifier): Trained from scratch, and its distribution is also aligned with MK-MMD. The class loss is computed only on labeled source images.

The squared MK-MMD between two distributions pp (source) and qq (target) is the distance between their means when the features are mapped into the space determined by the kernel kk (the reproducing kernel Hilbert space Hk\mathcal{H}_k) (Eq. (1) of the paper).

dk2(p,q)=∥Ep[ϕ(xs)]−Eq[ϕ(xt)]∥Hk2d_k^2(p, q) = \left\| \mathbb{E}_p[\phi(\boldsymbol{x}^s)] - \mathbb{E}_q[\phi(\boldsymbol{x}^t)] \right\|_{\mathcal{H}_k}^2

The kernel kk is a weighted sum of mm kernels kuk_u (Eq. (2)).

k=∑u=1mβuku,∑u=1mβu=1,βu≥0k = \sum_{u=1}^{m} \beta_u k_u, \qquad \sum_{u=1}^{m} \beta_u = 1, \quad \beta_u \ge 0

For kuk_u, Gaussian kernels ku(xi,xj)=e−∥xi−xj∥2/γuk_u(\boldsymbol{x}_i, \boldsymbol{x}_j) = e^{-\|\boldsymbol{x}_i - \boldsymbol{x}_j\|^2 / \gamma_u} with different widths (bandwidths) γu\gamma_u are used. The loss minimized in training is the class loss plus the MK-MMD from layer l1l_1 to layer l2l_2 (Eq. (4)).

min⁡Θ  1na∑i=1naJ(θ(xia),yia)+λ∑ℓ=l1l2dk2(Dsℓ,Dtℓ)\min_{\Theta} \; \frac{1}{n_a} \sum_{i=1}^{n_a} J(\theta(\boldsymbol{x}_i^a), y_i^a) + \lambda \sum_{\ell = l_1}^{l_2} d_k^2(\mathcal{D}_s^\ell, \mathcal{D}_t^\ell)

Here, JJ is cross-entropy, θ(xia)\theta(\boldsymbol{x}_i^a) is the CNN's predicted probability for the labeled image xia\boldsymbol{x}_i^a, Dsℓ\mathcal{D}_s^\ell and Dtℓ\mathcal{D}_t^\ell are the source and target features at layer ℓ\ell, and λ>0\lambda > 0 is the weight of MK-MMD. The paper uses l1=6l_1 = 6, l2=8l_2 = 8 (fc6-fc8).

Computed directly, MK-MMD evaluates the kernel for every pair of points, so its cost is quadratic in the number of samples nn. DAN computes the following gkg_k for each quadruple of two source points and two target points zi=(x2i−1s,x2is,x2i−1t,x2it)\boldsymbol{z}_i = (\boldsymbol{x}_{2i-1}^s, \boldsymbol{x}_{2i}^s, \boldsymbol{x}_{2i-1}^t, \boldsymbol{x}_{2i}^t), and estimates dk2d_k^2 without bias by their average (Section 3.2).

gk(zi)=k(x2i−1s,x2is)+k(x2i−1t,x2it)−k(x2i−1s,x2it)−k(x2is,x2i−1t)g_k(\boldsymbol{z}_i) = k(\boldsymbol{x}_{2i-1}^s, \boldsymbol{x}_{2i}^s) + k(\boldsymbol{x}_{2i-1}^t, \boldsymbol{x}_{2i}^t) - k(\boldsymbol{x}_{2i-1}^s, \boldsymbol{x}_{2i}^t) - k(\boldsymbol{x}_{2i}^s, \boldsymbol{x}_{2i-1}^t) dk2(p,q)=2ns∑i=1ns/2gk(zi)d_k^2(p, q) = \frac{2}{n_s} \sum_{i=1}^{n_s/2} g_k(\boldsymbol{z}_i)

Kernel values (degrees of similarity) within the same domain are added, and those across domains are subtracted. If points from the two domains are scattered in the same way, the added and subtracted terms cancel and the value approaches 0. The cost is linear in nn and decomposes into sums over minibatches, so it can be trained with ordinary backpropagation.

The kernel weights β\beta are also re-selected during training. DAN alternates between a step that updates the network weights Θ\Theta with minibatch SGD and a step that solves a quadratic program (Eq. (8) of the paper) for β\beta so that the power of the test distinguishing the two distributions is maximized (the Type II error is minimized).

Why it works

The DAN paper shows that the target error ϵt\epsilon_t has the following upper bound (Theorem 1).

ϵt(θ)≤ϵs(θ)+2dk(p,q)+C\epsilon_t(\theta) \le \epsilon_s(\theta) + 2 d_k(p, q) + C

ϵs\epsilon_s is the source error, and CC is a constant determined by factors such as the complexity of the hypothesis space. If features are learned that classify well on the source (small ϵs\epsilon_s) and also have a small MK-MMD dkd_k between the two domains, the upper bound on the target error decreases. DAN's loss (Eq. (4)) minimizes these two simultaneously.

The reason for aligning multiple layers is that more than one layer is hard to transfer. fc6-fc8 are all specialized to the original task, so aligning just one layer leaves domain differences in the others. The paper states that aligning the feature layers together with the classifier layer fc8 bridges not only the difference in input distributions (marginal distributions) but also the difference in how classes are predicted (conditional distributions).

The reason for using multiple kernels is that the differences that can be captured depend on the kernel width. A narrow kernel responds to fine differences between nearby points, and a wide kernel to coarse overall differences. Combining kernels of different widths makes it possible to measure differences not only in the mean (first-order statistics) but also in higher-order statistics such as spread.

In the paper's analysis of the A-distance (a measure of domain difference derived from the error of a classifier distinguishing source from target), pretrained CNN features actually made the domains easier to distinguish than raw features. Deep features help distinguish classes but also accentuate domain differences; with DAN's features, this A-distance is smaller than with CNN features.

Training setup and results

The main experimental settings in the paper are as follows.

  • All labeled source images and unlabeled target images are used (unsupervised adaptation).
  • The base width γ\gamma of the Gaussian kernel is set to the median of pairwise distances in the training data. MK-MMD combines Gaussian kernels with widths from 2−8γ2^{-8}\gamma to 28γ2^{8}\gamma in multiplicative steps of 21/22^{1/2}.
  • The MK-MMD weight λ\lambda is selected on validation data consisting of labeled source images and unlabeled target images.
  • The learning rate of the newly trained classifier fc8 is 10 times that of the other layers. Optimization is SGD with momentum 0.9.

Accuracy (%) on Office-31, consisting of images of 31 classes of office products, is as follows (Table 1 of the paper). A is Amazon (product photos from an online store), W is Webcam, and D is photos taken with a DSLR.

MethodA→WD→WW→DA→DD→AW→AAvg
CNN (only fine-tuned on source)61.695.499.063.851.149.870.1
DDC61.895.098.564.452.152.270.6
DAN (single layer, fc7 only)63.294.898.965.252.352.171.1
DAN (single kernel only)63.395.699.065.953.252.171.5
DAN68.596.099.067.054.053.172.9

Both the "single layer" and "single kernel" variants outperform DDC, and DAN, which combines both, is the highest. The gap is small for D→W and W→D, where the domains are very similar, and large for A→W, where they differ more. In experiments using the 10 classes shared by Office-31 and Caltech-256 (Table 2), the averages were also 84.0% for CNN, 84.6% for DDC, and 87.3% for DAN.

Varying the MK-MMD weight λ\lambda makes accuracy rise and then fall in a bell shape (Figure 3(b) of the paper, examined for λ\lambda from 0.1 to 2). Too small, and the domains are not aligned; too large, and the ability to distinguish classes drops. The paper describes a way to select λ\lambda without target labels (by looking jointly at the errors of the source classifier and a domain classifier), and following it is the safe choice.

Practical considerations

  • Match the kernel width to the scale of the features. If the Gaussian kernel width is too small or too large relative to feature distances, the kernel values become nearly constant and differences cannot be measured. As in the paper, use the median distance as the reference and combine kernels over a wide range of multipliers.
  • Be careful how minibatches are built. The linear-time estimate is computed over quadruples of two source and two target points, so put equal, even numbers of source and target images in each minibatch.
  • Which layers to align depends on the setting. The paper aligns fc6-fc8 but notes that other combinations of layers are possible depending on the number of source labels and the number of parameters in the fine-tuned layers.
  • What gets aligned is the overall feature distribution. There is no guarantee that per-class distributions align, so when class proportions differ greatly between source and target, aligning the whole can instead shift class boundaries.

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

DAN keeps DDC's approach of "adding a distance to the loss" while widening the layers aligned and the differences that can be measured. Because it does not train a discriminator, it tends to train more stably than adversarial methods (DANN, ADDA), but there are more things to decide than in DDC, such as kernel widths and how to choose β\beta. For simplicity, DDC or Deep CORAL are candidates; to align even differences in distribution shape by a distance, DAN; and to reduce every difference a discriminator can detect, DANN or ADDA.

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, models, transforms
from torch.utils.data import DataLoader

"""
Unsupervised domain adaptation from Office-31 Amazon (source, labeled) to Webcam (target, unlabeled).
Place images in per-class folders, such as office31/amazon/<class name>/*.jpg.
Webcam labels are used only for evaluation.
For simplicity, the kernel weights beta are fixed to be equal (the paper re-selects them with a quadratic program)
"""

batch_size = 32     # batch size for each of source and target (even, to form quadruples)
epochs = 20
lam = 1.0           # MK-MMD weight lambda (the paper selects it on validation data)
num_classes = 31

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

transform = transforms.Compose([
  transforms.Resize((227, 227)),
  transforms.ToTensor(),
  transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),
])
source = datasets.ImageFolder('./office31/amazon', transform=transform)
target = datasets.ImageFolder('./office31/webcam', 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, batch_size=256)


def mk_mmd_linear(hs, ht):
  """Linear-time estimate of MK-MMD^2 (quadruples z_i in Section 3.2 of the paper).
  33 widths from 2^-8 gamma to 2^8 gamma (in steps of 2^(1/2)) based on the median distance gamma; beta is equal"""
  gamma = torch.cdist(hs, ht).pow(2).median().detach()
  widths = [gamma * 2 ** (e / 2) for e in range(-16, 17)]

  def k(a, b):  # kernel values between corresponding rows, k(a_i, b_i)
    d2 = (a - b).pow(2).sum(dim=1)
    return sum(torch.exp(-d2 / w) for w in widths) / len(widths)

  s1, s2 = hs[0::2], hs[1::2]
  t1, t2 = ht[0::2], ht[1::2]
  return (k(s1, s2) + k(t1, t2) - k(s1, t2) - k(s2, t1)).mean()


class DAN(nn.Module):
  def __init__(self):
    super().__init__()
    alexnet = models.alexnet(weights=models.AlexNet_Weights.IMAGENET1K_V1)
    self.features = alexnet.features
    for p in self.features[:8].parameters():   # freeze conv1-conv3
      p.requires_grad = False
    self.avgpool = alexnet.avgpool
    c = alexnet.classifier
    self.fc6 = nn.Sequential(c[0], c[1], c[2])  # Dropout, Linear, ReLU
    self.fc7 = nn.Sequential(c[3], c[4], c[5])
    self.fc8 = nn.Linear(4096, num_classes)     # classifier (newly trained)

  def forward(self, x):
    h6 = self.fc6(torch.flatten(self.avgpool(self.features(x)), 1))
    h7 = self.fc7(h6)
    logits = self.fc8(h7)
    return logits, [h6, h7, F.softmax(logits, dim=1)]  # representations of the 3 layers to align


model = DAN().to(device)
pretrained = [p for n, p in model.named_parameters() if p.requires_grad and not n.startswith('fc8')]
optimizer = optim.SGD([
  {'params': pretrained, 'lr': 1e-3},
  {'params': model.fc8.parameters(), 'lr': 1e-2},   # 10x for the newly trained layer
], momentum=0.9)

for epoch in range(epochs):
  model.train()   # dropout in fc6 and fc7 is active
  for (xs, ys), (xt, _) in zip(source_loader, target_loader):
    xs, ys, xt = xs.to(device), ys.to(device), xt.to(device)
    logits, hidden = model(torch.cat([xs, xt]))
    n = len(xs)
    loss_cls = F.cross_entropy(logits[:n], ys)                       # source only
    loss_mmd = sum(mk_mmd_linear(h[:n], h[n:]) for h in hidden)      # sum over fc6-fc8
    loss = loss_cls + lam * loss_mmd                                 # Eq. (4)

    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

model.eval()      # disable dropout
correct = total = 0
with torch.no_grad():
  for images, labels in test_loader:
    images, labels = images.to(device), labels.to(device)
    predicted = model(images)[0].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 MMD and MK-MMD?
A.

MMD is the distance between the means of features mapped with a single kernel. MK-MMD is MMD using a kernel k=∑uβukuk = \sum_u \beta_u k_u that sums multiple Gaussian kernels of different widths with weights βu\beta_u. Since the scale of difference a kernel responds to depends on its width, combining several reduces the chance of missing differences by picking the wrong width. In the DAN paper, DAN with MK-MMD scored higher on the Office-31 average than the variant using a single kernel (72.9% vs. 71.5%).

Q. Why are the convolutional layers not aligned?
A.

Because convolutional features already transfer well across domains. The DAN paper freezes conv1-conv3 as general features, only fine-tunes conv4-conv5 since they are slightly biased, and applies MK-MMD only to the fully connected layers fc6-fc8, which are specialized to the original task. Aligning more layers also increases computation, so focusing on hard-to-transfer layers is reasonable.

Q. Can it be used when a few target labels are available?
A.

Yes. In that case, the class loss is computed on both labeled source and target images (xia\boldsymbol{x}_i^a in Eq. (3) of the paper covers images from both domains). In Table 3 of the paper, with 3 target labels per class, the average over Office-31 A→W, D→W, and W→D was 93.1% for DAN versus 91.9% for DDC.

References

  1. Long, M., Cao, Y., Wang, J., & Jordan, M. I. (2015). Learning Transferable Features with Deep Adaptation Networks. Proceedings of the 32nd International Conference on Machine Learning (ICML), PMLR 37.
  2. Tzeng, E., Hoffman, J., Zhang, N., Saenko, K., & Darrell, T. (2014). Deep Domain Confusion: Maximizing for Domain Invariance. arXiv:1412.3474.