DANN (Domain-Adversarial Neural Network) is a domain adaptation method that makes a model trained on labeled data (the source) usable on unlabeled data with different characteristics (the target). Ganin and Lempitsky proposed it in 2015, and a paper with additional theory and experiments was published in JMLR in 2016.
For example, synthetic digit images (the source) may have plenty of labels while real photos of digits (the target) have none. A model trained only on the source and applied directly to the target loses much of its accuracy because of differences such as background and color (domain shift).
DANN addresses this by learning features from which it cannot be told which domain the image came from. The idea is that if features cannot be distinguished between source and target, a classifier learned on the source should work on the target as is. Domain adaptation theory (the results of Ben-David et al.), which states that the smaller the difference between the two domains, the smaller the upper bound on target error, supports this idea.
To do this, DANN adds a "domain classifier" that predicts the domain from the features and performs adversarial training: the classifier tries to tell the domains apart, while the feature extractor tries to make them indistinguishable. This resembles the relationship between the generator and discriminator of a GAN, but DANN's distinguishing feature is that it achieves this within ordinary backpropagation simply by inserting a single layer, the gradient reversal layer. For this reason, "gradient reversal," as in the title, is used almost as another name for the method.
Network structure and the gradient reversal layer
As in Figure 1 of the paper, the DANN network consists of three parts.
Feature extractor Gf (parameters θf): maps the input x to features f. Both source and target images pass through it.
Label predictor Gy (parameters θy): predicts the class from the features. The loss is computed only on labeled source images.
Domain classifier Gd (parameters θd): predicts from the features whether an image is from the source or the target (di=0 or 1). The loss is computed on all images. A gradient reversal layer sits between it and the feature extractor.
Here, Lyi is the class loss of the i-th image (e.g., multiclass cross-entropy), Ldi is the domain loss (binary cross-entropy), and λ is a coefficient that balances the two losses. DANN seeks a saddle point of this E.
In other words, the domain classifier θd moves to decrease the domain loss (increase E), while the feature extractor θf moves to decrease the class loss and increase the domain loss.
The gradient reversal layer Rλ performs this "decrease one, increase the other" in a single backward pass.
Rλ(x)=x,dxdRλ=−λI
In the forward pass it passes the input through unchanged; in the backward pass it multiplies the incoming gradient by −λ before passing it to the previous layer (I is the identity matrix). The domain classifier itself is updated normally to lower the domain loss, but the feature extractor before the gradient reversal layer receives a gradient pointing in the opposite direction. As a result, the feature extractor is updated in the direction that "makes domains harder to tell apart."
The gradient reversal layer has no learnable parameters and takes only a few lines to write. Any existing classification model becomes DANN by attaching a gradient reversal layer and a domain classifier to its feature output. At inference, only the feature extractor and the label predictor are used.
Training setup and results
In the paper, the weight λ of the domain loss starts at 0 at the beginning of training and gradually approaches 1.
λp=1+exp(−γ⋅p)2−1
Here, p is the training progress (increasing linearly from 0 to 1) and γ controls how fast it rises; γ=10 in all experiments. Early in training, the features are not yet useful and the domain classifier's signal is close to noise, so its influence is suppressed.
The learning rate μp is also lowered as training progresses.
μp=(1+α⋅p)βμ0,μ0=0.01,α=10,β=0.75
Optimization uses SGD with momentum 0.9 and a batch size of 128 (half source images, half target images).
Because training is adversarial, it becomes unstable if λ is too large or the domain classifier is too strong or too weak. In addition, DANN aligns the distribution of the features as a whole, which does not guarantee that the per-class distributions are aligned. When class proportions differ greatly between source and target, for example, aligning the features can actually shift the class boundaries.
The results of the digit and traffic sign experiments in the 2015 paper (ICML), measured as accuracy on the unlabeled target, are shown below. The values in parentheses indicate how much of the gap between "no adaptation" and "the upper bound trained with target labels" was closed.
Adversarial training with the GAN loss. Fixes the extractor trained on the source and trains a separate extractor for the target
Separate per domain
Methods that "compute a distance directly," such as MMD and CORAL, tend to train stably, but they align only the chosen statistics. Adversarial methods such as DANN and ADDA try to reduce any difference the classifier can detect, which makes them more expressive, but their training stability needs care.
PyTorch example
▶Show code
python
import math
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
from tqdm import tqdm
"""
Domain adaptation from MNIST (source, labeled) to USPS (target, unlabeled).
USPS labels are used only for evaluation
"""
# Hyperparameters (λ and learning rate schedules follow the paper)
batch_size = 64 # batch size for each of source and target
epochs = 10 # number of epochs
mu0, alpha, beta = 0.01, 10, 0.75 # learning rate μp = μ0 / (1 + α p)^β
gamma = 10 # λp = 2 / (1 + exp(-γ p)) - 1
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 16×16, so resize to 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)
# Gradient reversal layer: identity in the forward pass, multiplies the gradient by -λ in the backward pass
class GradReverse(torch.autograd.Function):
@staticmethod
def forward(ctx, x, lam):
ctx.lam = lam
return x.view_as(x)
@staticmethod
def backward(ctx, grad_output):
return -ctx.lam * grad_output, None
class DANN(nn.Module):
def __init__(self):
super().__init__()
self.features = nn.Sequential( # feature extractor G_f
nn.Conv2d(1, 32, 5), nn.ReLU(), nn.MaxPool2d(2),
nn.Conv2d(32, 48, 5), nn.ReLU(), nn.MaxPool2d(2),
nn.Flatten(), # [B, 48 * 4 * 4]
)
self.label_predictor = nn.Sequential( # label predictor G_y
nn.Linear(48 * 4 * 4, 100), nn.ReLU(),
nn.Linear(100, 10),
)
self.domain_classifier = nn.Sequential( # domain classifier G_d
nn.Linear(48 * 4 * 4, 100), nn.ReLU(),
nn.Linear(100, 1), # source (0) or target (1)
)
def forward(self, x, lam=0.0):
f = self.features(x)
return self.label_predictor(f), self.domain_classifier(GradReverse.apply(f, lam))
model = DANN().to(device)
optimizer = optim.SGD(model.parameters(), lr=mu0, momentum=0.9)
total_steps = epochs * min(len(source_loader), len(target_loader))
step = 0
for epoch in tqdm(range(epochs)):
model.train()
for (xs, ys), (xt, _) in zip(source_loader, target_loader):
p = step / total_steps # training progress (0→1)
lam = 2 / (1 + math.exp(-gamma * p)) - 1
for group in optimizer.param_groups:
group['lr'] = mu0 / (1 + alpha * p) ** beta
xs, ys, xt = xs.to(device), ys.to(device), xt.to(device)
x = torch.cat([xs, xt])
d = torch.cat([torch.zeros(len(xs)), torch.ones(len(xt))]).to(device)
class_logits, domain_logits = model(x, lam)
loss_y = F.cross_entropy(class_logits[:len(xs)], ys) # source only
loss_d = F.binary_cross_entropy_with_logits(domain_logits.squeeze(1), d) # all images
loss = loss_y + loss_d # λ is applied inside the gradient reversal layer
optimizer.zero_grad()
loss.backward()
optimizer.step()
step += 1
# Evaluate on the target (USPS) test data
model.eval()
correct = 0
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. Can't I just add −λL_d to the loss instead of using a gradient reversal layer?
A.
Then the domain classifier would also be updated to increase the domain loss, and it would never learn to discriminate. In DANN, the classifier must decrease the domain loss while only the feature extractor increases it. The gradient reversal layer achieves this in a single backward pass by sending the reversed gradient only to the layers before the classifier.
Q. Are no target labels needed at all?
A.
None are needed for training. DANN is an "unsupervised domain adaptation" method in which the target has no labels at all. However, having a few target labels for evaluation is reassuring for choosing hyperparameters and checking whether adaptation worked.
Q. Can it be used for data other than images?
A.
Yes. The gradient reversal layer and domain classifier can be attached to any network that produces features. Besides image classification, the JMLR paper also applies it to document sentiment analysis (adaptation between product categories) and person re-identification.