AI Logic

Domain Adaptation

Deep CORAL

Updated๏ผš

The training flow of Deep CORAL. Left: source and target images pass through a shared feature extractor and the classification layer fc8, then branch into the class loss and the CORAL loss. Right: source and target feature points spread in different directions, their respective covariance matrices, and the formula for the CORAL loss

Background and overview

Deep CORAL is a domain adaptation method that adds the difference between the covariance matrices of source and target features to the loss, aligning how the two domains' features "spread." It was proposed by Sun and Saenko in 2016. CORAL stands for Correlation Alignment.

A model trained on labeled data (the source) loses accuracy on unlabeled data of a different nature (the target) because of differences in background, capture conditions, image quality, and so on (domain shift). The original CORAL (proposed by Sun et al. in 2016) was known as a "frustratingly easy" method that applies a linear transformation to source features to match their covariance (second-order statistics) to the target. However, CORAL was split into separate stages of extracting features, transforming them, and classifying with an SVM, so the network could not be trained end to end.

Deep CORAL turns this idea of "matching covariances" into a differentiable loss (the CORAL loss) and builds it into the training of a deep network.

  • The two domains can be aligned not only with a linear transformation but with a nonlinear transformation learned by the network.
  • Since it only adds one loss, it can be built into any layer of any network.

The paper argues that, compared with DDC and DAN, which also add a loss, it is stronger than DDC (aligning not only the mean but the covariance) and easier to optimize than DAN or DANN.

Computing the CORAL loss

Let dd be the feature dimension of a layer, DSD_S (nSร—dn_S \times d) the matrix of source features, and DTD_T (nTร—dn_T \times d) the matrix of target features. The CORAL loss is computed as follows (Section 3.1 of the paper).

  1. Extract source and target features by passing each through the network with the same weights.
  2. Compute their covariance matrices CSC_S and CTC_T (both dร—dd \times d) (Eqs. (2)(3)).
  3. Divide the sum of squared elements of the difference between the two covariance matrices (the squared Frobenius norm) by 4d24d^2 (Eq. (1)).
CS=1nSโˆ’1(DSโŠคDSโˆ’1nS(1โŠคDS)โŠค(1โŠคDS))C_S = \frac{1}{n_S - 1}\left( D_S^\top D_S - \frac{1}{n_S} (\mathbf{1}^\top D_S)^\top (\mathbf{1}^\top D_S) \right) โ„“CORAL=14d2โˆฅCSโˆ’CTโˆฅF2\ell_{\mathrm{CORAL}} = \frac{1}{4d^2} \left\| C_S - C_T \right\|_F^2

1\mathbf{1} is a column vector of all ones, and CTC_T is computed the same way with DTD_T and nTn_T. The term 1nS(1โŠคDS)โŠค(1โŠคDS)\frac{1}{n_S}(\mathbf{1}^\top D_S)^\top(\mathbf{1}^\top D_S) subtracts the mean. Covariances are computed on the images within a minibatch.

The diagonal elements of a covariance matrix represent the spread of each dimension, and the off-diagonal elements represent how much two dimensions vary together (correlation). Reducing the CORAL loss makes the spread of each feature dimension and the correlations between dimensions match between source and target.

Training minimizes the classification loss plus the CORAL loss (Eq. (6)).

โ„“=โ„“CLASS+โˆ‘i=1tฮปiโ€‰โ„“CORAL\ell = \ell_{\mathrm{CLASS}} + \sum_{i=1}^{t} \lambda_i \, \ell_{\mathrm{CORAL}}

tt is the number of layers to which the CORAL loss is applied, and ฮปi\lambda_i is its weight. The classification loss is computed only on labeled source images.

In the example in Figure 1 of the paper, the CORAL loss is applied to the output of AlexNet's last classification layer fc8 (with as many dimensions as classes). Most classification networks end with a fully connected classification layer, so it is the most general place to put it. It can also be built into other layers and networks as is.

Why it works

The classification loss and the CORAL loss pull against each other.

  • Reducing only the classification loss makes the features fit the source too closely (overfitting), lowering accuracy on the target.
  • Reducing only the CORAL loss can drive the loss to 0, for example by mapping all images to a single point, but such features cannot distinguish classes.

Reducing both together yields features that distinguish classes and have the same spread for source and target. The paper states that the two losses reach an equilibrium by the end of training.

The analysis of Aโ†’W (from online-store product photos to webcam photos) in Figure 2 of the paper shows the following.

  • Adding the CORAL loss greatly increased target accuracy with almost no loss of source accuracy.
  • Because the classification layer fc8 is initialized with small values, the CORAL loss is very small and the classification loss very large at the start of training. After a few hundred updates, the two losses became about the same size.
  • When trained with the CORAL loss weight set to 0, the covariance distance between source and target kept growing, to more than 100 times that of training with the CORAL loss. This shows that fine-tuning without domain adaptation tends to make features overfit the source.

Training setup and results

The paper's experiments were run on the Office dataset, consisting of images of 31 classes of office products. It uses the six pairs of three domains: Amazon (A, product photos from an online store), DSLR (D, photos taken with a DSLR camera), and Webcam (W, photos taken with a webcam). The settings are as follows.

  • All labeled source images and unlabeled target images are used (unsupervised adaptation).
  • The network is initialized with the weights of Caffe's BVLC Reference CaffeNet pretrained on ImageNet, except that the classification layer fc8 is initialized from a normal distribution with mean 0 and standard deviation 0.005. The learning rate of fc8 is 10 times that of the other layers.
  • The batch size is 128, the base learning rate is 10โˆ’310^{-3}, weight decay is 5ร—10โˆ’45 \times 10^{-4}, and momentum is 0.9.
  • The CORAL loss weight ฮป\lambda is set so that the classification loss and the CORAL loss are about the same size at the end of training.

Accuracy (%) evaluated on the unlabeled target is as follows (Table 1 of the paper).

MethodAโ†’DAโ†’WDโ†’ADโ†’WWโ†’AWโ†’DAvg
CNN (no adaptation)63.861.651.195.449.899.070.1
CORAL (linear transformation + SVM)65.764.348.596.148.299.870.4
DDC64.461.852.195.052.298.570.6
DAN (fc8 only)65.863.852.894.651.998.871.3
Deep CORAL66.866.452.895.751.599.272.1

Deep CORAL is the highest on average and achieved the highest accuracy on three of the six pairs. On the remaining three, it is within 0.7 points of the best method. For a fair comparison, DAN in this table aligns only the fc8 layer, like Deep CORAL.

Practical considerations

The paper sets the CORAL loss weight ฮป\lambda so that it "is about the same size as the classification loss at the end of training." There is no fixed value, so when the network or data changes, tune it while watching how the magnitudes of the two losses evolve. If it is too large, the features may collapse into a form that makes classes hard to distinguish.

  • Alignment goes only up to second-order statistics (covariance). Eqs. (2)(3) subtract the mean before computing the covariance, so the CORAL loss itself does not measure mean shifts. It also cannot measure finer differences in distribution shape.
  • Covariance is estimated per minibatch. With few images in a minibatch relative to the feature dimension dd, covariance estimates become noisy. The paper applies the loss to the 31-dimensional fc8 with batch size 128.
  • Computation grows for high-dimensional layers. The covariance matrix is dร—dd \times d, so applying it to a 4096-dimensional layer, for example, gives about 17 million matrix elements.
  • 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

Like DDC, Deep CORAL can be used by "just adding one loss," and its only hyperparameter to decide is ฮป\lambda. Whereas DDC aligns mean shifts, Deep CORAL aligns spread and correlation. The paper notes that minimizing the CORAL loss is similar to minimizing MMD with a polynomial kernel. To align distribution shape including the choice of kernels, DAN is a candidate; to reduce every difference a discriminator can detect, DANN or ADDA; but both require deciding more than Deep CORAL.

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 = 1.0           # CORAL loss weight lambda; tune so the two losses are about equal at the end of training
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 covariance(D):
  """Eq. (2)(3): C = (Dแต€D โˆ’ (1แต€D)แต€(1แต€D) / n) / (n โˆ’ 1). D is [n, d]"""
  n = D.size(0)
  s = D.sum(dim=0, keepdim=True)          # 1แต€D  [1, d]
  return (D.t() @ D - s.t() @ s / n) / (n - 1)


def coral_loss(Ds, Dt):
  """Eq. (1): โ€–C_S โˆ’ C_Tโ€–ยฒ_F / (4 dยฒ)"""
  d = Ds.size(1)
  return (covariance(Ds) - covariance(Dt)).pow(2).sum() / (4 * d * d)


model = models.alexnet(weights=models.AlexNet_Weights.IMAGENET1K_V1)
fc8 = nn.Linear(4096, num_classes)        # create a new classification layer, initialized with N(0, 0.005)
nn.init.normal_(fc8.weight, 0, 0.005)
nn.init.zeros_(fc8.bias)
model.classifier[6] = fc8
model = model.to(device)

optimizer = optim.SGD([
  {'params': [p for n, p in model.named_parameters() if not n.startswith('classifier.6')], 'lr': 1e-3},
  {'params': fc8.parameters(), 'lr': 1e-2},   # 10x learning rate for fc8
], momentum=0.9, weight_decay=5e-4)

for epoch in range(epochs):
  model.train()   # dropout is active
  for (xs, ys), (xt, _) in zip(source_loader, target_loader):
    xs, ys, xt = xs.to(device), ys.to(device), xt.to(device)
    out = model(torch.cat([xs, xt]))      # fc8 output (weights shared by the two domains)
    out_s, out_t = out[:len(xs)], out[len(xs):]
    loss_class = F.cross_entropy(out_s, ys)       # source only
    loss_coral = coral_loss(out_s, out_t)         # all images
    loss = loss_class + lam * loss_coral          # Eq. (6) (t = 1)

    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
  print(f"epoch {epoch}: class {loss_class.item():.3f}  coral {lam * loss_coral.item():.3f}")

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).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 CORAL and Deep CORAL?
A.

They differ in how they align and how they are trained. CORAL applies a linear transformation to features extracted from a trained network to match the source covariance to the target, and then classifies separately with an SVM. Deep CORAL builds the covariance difference into network training as a loss, so the network itself learns to align the two domains with a nonlinear transformation. In the paper's Office experiments, average accuracy was 72.1% for Deep CORAL versus 70.4% for CORAL.

Q. Does it not align mean shifts?
A.

The CORAL loss itself does not, because Eqs. (2)(3), which compute the covariance, subtract the mean first. To also align mean shifts, one could combine it with, for example, the MMD loss of DDC, which measures the difference of means, but that is not a setting evaluated in the paper.

Q. Which layer should the CORAL loss be applied to?
A.

In the paper's experiments, it is applied to the output of the last classification layer fc8. Most classification networks have this layer, and its dimension is small (the number of classes), so computing the covariance matrix is cheap. As in Eq. (6), it can be applied to multiple layers, and the paper says building it into other layers and networks is easy, but it does not show experimental results for that.

References

  1. Sun, B., & Saenko, K. (2016). Deep CORAL: Correlation Alignment for Deep Domain Adaptation. Computer Vision โ€“ ECCV 2016 Workshops, Lecture Notes in Computer Science, 443โ€“450.
  2. Sun, B., Feng, J., & Saenko, K. (2016). Return of Frustratingly Easy Domain Adaptation. AAAI 2016.
  3. Tzeng, E., Hoffman, J., Zhang, N., Saenko, K., & Darrell, T. (2014). Deep Domain Confusion: Maximizing for Domain Invariance. arXiv:1412.3474.
  4. 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.