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.
conv1-conv3: These are general features that apply to any data, so they are frozen at the pretrained weights.
conv4-conv5: These begin to be slightly domain-biased, so they are fine-tuned.
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.
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 p (source) and q (target) is the distance between their means when the features are mapped into the space determined by the kernel k (the reproducing kernel Hilbert space Hk) (Eq. (1) of the paper).
dk2(p,q)=Ep[ϕ(xs)]−Eq[ϕ(xt)]Hk2
The kernel k is a weighted sum of m kernels ku (Eq. (2)).
k=u=1∑mβuku,u=1∑mβu=1,βu≥0
For ku, Gaussian kernels ku(xi,xj)=e−∥xi−xj∥2/γu with different widths (bandwidths) γu are used. The loss minimized in training is the class loss plus the MK-MMD from layer l1 to layer l2 (Eq. (4)).
Here, J is cross-entropy, θ(xia) is the CNN's predicted probability for the labeled image xia, Dsℓ and Dtℓ are the source and target features at layer ℓ, and λ>0 is the weight of MK-MMD. The paper uses l1=6, l2=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 n. DAN computes the following gk for each quadruple of two source points and two target points zi=(x2i−1s,x2is,x2i−1t,x2it), and estimates dk2 without bias by their average (Section 3.2).
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 n and decomposes into sums over minibatches, so it can be trained with ordinary backpropagation.
The kernel weights β are also re-selected during training. DAN alternates between a step that updates the network weights Θ with minibatch SGD and a step that solves a quadratic program (Eq. (8) of the paper) for β 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 has the following upper bound (Theorem 1).
ϵt(θ)≤ϵs(θ)+2dk(p,q)+C
ϵs is the source error, and C 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) and also have a small MK-MMD dk 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 γ 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γ to 28γ in multiplicative steps of 21/2.
The MK-MMD weight λ 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.
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 λ makes accuracy rise and then fall in a bell shape (Figure 3(b) of the paper, examined for λ 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 λ 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."
Adversarial training with the same loss as a GAN. The extractor trained on the source is frozen, and a separate target extractor is trained
Separate 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 β. 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βuku that sums multiple Gaussian kernels of different widths with weights β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 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.