DDC (Deep Domain Confusion) is a domain adaptation method that makes a CNN trained on labeled data (the source) usable on data of a different nature that has no or only a few labels (the target). It was proposed by Tzeng et al. in 2014. It works simply by adding one low-dimensional "adaptation layer" to the CNN and adding the difference between source and target means (MMD) of that layer's features to the loss.
For example, product photos from an online store (the source) may have many labels, while photos taken by a webcam in an office (the target) have none. Even with a CNN pretrained on ImageNet, differences in background, resolution, lighting, and so on (domain shift) make a classifier learned on the source lose accuracy on the target.
DDC solves this problem with the idea that "if source and target features are scattered in the same way, a classifier learned on the source should work as is on the target." To that end, it fine-tunes a pretrained CNN to reduce the classification loss while also reducing the distance between the two domains' features. The paper describes this as "making the domains hard to distinguish (maximizing domain confusion)," which is where the method's name comes from.
DDC is an early method in the line of deep domain adaptation that "adds a distance between feature distributions to the loss," and later methods such as DAN and Deep CORAL extend this form.
Network architecture and loss
As in Figure 1 of the paper, DDC's network is AlexNet (5 convolutional and 3 fully connected layers) with one adaptation layer added.
Feature extractor: conv1-fc7 of a pretrained AlexNet. Both source and target images pass through it, and the weights are shared between the two domains.
Adaptation layer fc_adapt: A low-dimensional fully connected layer added after fc7. Squeezing to a low dimension aims to prevent fitting too closely to fine quirks of the source (overfitting).
Classifier fc8: Predicts classes from the adaptation layer's output. The class loss is computed only on labeled images.
MMD loss: Computes the distance between source and target on the adaptation layer's output. No labels are needed, so all images are used.
MMD (Maximum Mean Discrepancy) is used as the distance between the two domains. With Ļ(ā ) the output of the adaptation layer, XSā the set of source images, and XTā the set of target images, Eq. (1) of the paper is as follows.
In other words, it is the length of the difference between the mean of source features and the mean of target features. Training minimizes the following loss, which adds this to the class loss (Eq. (2)).
L=LCā(XLā,y)+Ī»MMD2(XSā,XTā)
Here, LCā is the classification loss (cross-entropy) on labeled images XLā and their ground truth y, and Ī» is a coefficient that determines how strongly the domains are confused. MMD is computed on the source and target images within a minibatch.
The position and width of the adaptation layer are also chosen by looking at MMD. First, the MMD of each fully connected layer is measured with the pretrained CNN as is, and the adaptation layer is placed after fc7, which had the smallest. Next, the network is trained with widths varied from 64 to 4096 in powers of 2, and 256 dimensions, which gives the smallest MMD after training, is chosen. The advantage is that the architecture can be decided without target labels.
Why it works
The target error of a classifier trained only on the source is known to increase as the difference between the two domains' input distributions grows (the theoretical and experimental results cited in Chapter 1 of the paper). DDC directly reduces this "distribution difference" on the features used for classification.
The class loss pushes the features to distinguish classes.
The MMD loss pushes source and target features to gather in the same region.
Reducing both simultaneously yields features that "cluster by class and do not separate by domain." In Figure 6 of the paper (a t-SNE plot of features in 2D), with features learned by DDC, Amazon and Webcam images of the same class mix in a single cluster. In contrast, with the pretrained fc7 features as is, the same class split into separate clusters per domain.
The MMD loss also acts as regularization. In Figure 5 of the paper, training without the MMD loss raised target accuracy quickly at first but soon overfit the source and accuracy dropped. Training with the MMD loss improved more slowly but reached a higher final accuracy.
Training setup and results
The paper's experiments were run on the Office dataset, consisting of images of 31 classes of office products. It has three domains: Amazon (product photos from an online store), DSLR (photos taken with a DSLR camera), and Webcam (photos taken with a webcam).
Source images: 20 per class for Amazon, and 8 per class for Webcam and DSLR.
Supervised adaptation uses only 3 target labels per class; unsupervised adaptation uses no target labels.
The classifier is trained on labeled images from both domains in supervised adaptation, and only on source images in unsupervised adaptation. In both cases, MMD is computed on all images.
Ī»=0.25. It was chosen to keep classification primary while being strong enough to prevent overfitting.
The learning rate of the newly added adaptation layer and classifier is 10 times that of the layers copied from pretraining.
Evaluation uses 5 random splits, and the average is reported.
Accuracy (%) evaluated on the unlabeled target is as follows (Tables 1 and 2 of the paper).
Setting
Method
AāW
DāW
WāD
Avg
Unsupervised
DeCAF6 (source only)
52.2
91.5
ā
ā
Unsupervised
DDC
59.4
92.5
91.7
81.2
Supervised (3 target labels/class)
DeCAF6 (source + target)
80.7
94.8
ā
ā
Supervised (3 target labels/class)
DDC
84.1
95.4
96.3
91.9
A is Amazon, W is Webcam, and D is DSLR. DeCAF6 is a baseline that uses the fc6 features of a pretrained CNN as is. DDC's gain is largest on AāW, where the domain gap is largest.
Results depend on the magnitude of Ī». Too small, and the MMD loss has almost no effect; too large, and the result is features in which all points collapse close together and classes cannot be distinguished. MMD can be driven to 0 by collapsing features to a single point, so balancing it against the class loss is essential.
Practical considerations
Only the mean is aligned. Eq. (1) is the difference of feature means, so it cannot distinguish distributions with the same mean but different spread (variance, covariance). The Deep CORAL paper characterizes DDC as "a method that aligns only the mean" and proposes a method that also aligns covariance.
Only one layer is aligned. The DAN paper points out that multiple layers, such as fc6-fc8, become hard to transfer, so aligning just one layer leaves differences.
MMD computed on minibatches is biased. The DAN paper states that computing MMD within a minibatch introduces bias into the estimate and lowers adaptation accuracy.
The size of the gain depends on the evaluation protocol. When the DAN paper re-compared methods using a protocol with all source labels, the average over the six Office pairs was 70.1% for a CNN that was only fine-tuned and 70.6% for DDC, a small gap.
Per-class distributions are not aligned. What gets aligned is the overall feature distribution, 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."
Method
What is aligned
How
Feature extractor
DDC
Feature distribution of one layer
Adds MMD (the difference of the two distributions' means) to the loss
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
DDC only adds "one adaptation layer and a loss that computes the difference of means," so it is the easiest to try. When the domain difference can be roughly explained by a shift in the mean (such as differences in resolution or lighting), DDC may be enough. To align even the shape of the distributions, DAN or Deep CORAL are candidates; to reduce every difference a discriminator can detect, DANN or ADDA. However, adversarial methods require attention to training stability.
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
"""
batch_size = 64 # batch size for each of source and target
epochs = 20
lam = 0.25 # MMD loss weight lambda (paper's value)
adapt_dim = 256 # adaptation layer width (256, selected by MMD in the paper)
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 mmd(fs, ft):
"""Eq. (1): norm of the difference between the source and target feature means (computed per minibatch)"""
return (fs.mean(dim=0) - ft.mean(dim=0)).norm()
class DDC(nn.Module):
def __init__(self):
super().__init__()
alexnet = models.alexnet(weights=models.AlexNet_Weights.IMAGENET1K_V1)
self.features = alexnet.features # conv1-conv5 (shared by the two domains)
self.avgpool = alexnet.avgpool
self.fc67 = alexnet.classifier[:6] # fc6, fc7 (including dropout and ReLU)
self.adapt = nn.Sequential(nn.Linear(4096, adapt_dim), nn.ReLU()) # adaptation layer fc_adapt
self.fc8 = nn.Linear(adapt_dim, num_classes) # classifier
def forward(self, x):
h = self.fc67(torch.flatten(self.avgpool(self.features(x)), 1))
f = self.adapt(h)
return self.fc8(f), f
model = DDC().to(device)
# Newly added layers (adaptation layer and classifier) use 10x the learning rate of layers copied from pretraining
optimizer = optim.SGD([
{'params': list(model.features.parameters()) + list(model.fc67.parameters()), 'lr': 1e-3},
{'params': list(model.adapt.parameters()) + list(model.fc8.parameters()), 'lr': 1e-2},
], 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, f = model(torch.cat([xs, xt]))
fs, ft = f[:len(xs)], f[len(xs):]
loss_c = F.cross_entropy(logits[:len(xs)], ys) # labeled source only
loss_mmd = mmd(fs, ft) ** 2 # all images
loss = loss_c + lam * loss_mmd # Eq. (2)
optimizer.zero_grad()
loss.backward()
optimizer.step()
# Evaluate on the target (Webcam). Inference uses only the adaptation layer and classifier; MMD is not computed
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. If MMD is driven to 0, will classification work well on the target?
A.
Not necessarily. The MMD in Eq. (1) is the difference of feature means, so it becomes 0 if all images are mapped to the same single point, but such features cannot distinguish classes. DDC minimizes it together with the class loss LCā to find features that distinguish classes and do not separate by domain. The paper also cautions that making Ī» too large gathers the points too close together.
Q. Can it be used when a few target labels are available?
A.
Yes. The paper also evaluates "supervised adaptation" with 3 target labels per class. In that case, the classifier is trained on labeled images from both source and target, and MMD is computed on all images regardless of labels. On Office AāW, accuracy was 84.1% with 3 labels per class, compared with 59.4% without labels.
Q. What is the difference between DDC and DAN?
A.
They differ in the number of layers aligned and in how the distance is measured. DDC reduces the difference of means (Eq. (1) of the paper) for the features of one adaptation layer. DAN aligns three layers, fc6-fc8, and uses MK-MMD, which combines multiple Gaussian kernels, to measure not only the mean but also differences in distribution shape. In the DAN paper, the average over the six Office-31 pairs was 72.9% for DAN versus 70.6% for DDC.