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 d be the feature dimension of a layer, DSโ (nSโรd) the matrix of source features, and DTโ (nTโรd) the matrix of target features. The CORAL loss is computed as follows (Section 3.1 of the paper).
Extract source and target features by passing each through the network with the same weights.
Compute their covariance matrices CSโ and CTโ (both dรd) (Eqs. (2)(3)).
Divide the sum of squared elements of the difference between the two covariance matrices (the squared Frobenius norm) by 4d2 (Eq. (1)).
1 is a column vector of all ones, and CTโ is computed the same way with DTโ and nTโ. The term nSโ1โ(1โคDSโ)โค(1โคDSโ) 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=1โtโฮปiโโCORALโ
t is the number of layers to which the CORAL loss is applied, and ฮป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.
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 ฮป 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 d, 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ร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."
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
Like DDC, Deep CORAL can be used by "just adding one loss," and its only hyperparameter to decide is ฮป. 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.