AI Logic

Loss Functions

Center Loss

Updated๏ผš

Diagram of Center Loss. Two panels show the distribution of 2-D features for four classes. The left panel is trained with the softmax loss only: the classes are separated, but the features radiate out from the origin and vary widely within each class. The right panel adds ฮป ยท Center Loss to the softmax loss: the features of each class gather near the centers c_1 to c_4, shown as white circles, and arrows show distant features being pulled toward their centers. A legend and the equation L = L_S + ฮป ยท ยฝฮฃโ€–x_i โˆ’ c_{y_i}โ€–ยฒ are on the far right

Background and overview

Center Loss is a loss function that learns a feature center for each class and reduces the distance between each sample's feature and the center of its class. It is used together with softmax cross-entropy (called the softmax loss in the paper) to gather features of the same class in one place. Wen, Zhang, Li, and Qiao (2016, ECCV) proposed it for face recognition.

Let xix_i be the output of the network's last hidden layer (the deep feature), yiy_i the class of that sample, and cjc_j the center of class jj. Center Loss is then

LC=12โˆ‘i=1mโˆฅxiโˆ’cyiโˆฅ22\mathcal{L}_C = \frac{1}{2} \sum_{i=1}^{m} \bigl\lVert x_i - c_{y_i} \bigr\rVert_2^2

where mm is the mini-batch size. Training minimizes L=LS+ฮปLC\mathcal{L} = \mathcal{L}_S + \lambda \mathcal{L}_C, the sum of the softmax loss LS\mathcal{L}_S and Center Loss weighted by ฮป\lambda.

Face recognition has to distinguish people not seen during training. For that, it is not enough for features to be "separated by class"; features of the same person must be "compact, and far from other people." The paper trained a network with 2-D features on MNIST and plotted them, showing that features learned with the softmax loss alone are separated but vary widely within each class. The left side of the figure at the top shows this, and the right side shows the features of each class gathered near their centers after adding Center Loss.

Theory (computing the loss and updating the centers)

Following Algorithm 1 of the paper, one training update proceeds as follows.

  1. Pass each sample of the mini-batch through the network to get the deep features xix_i.
  2. Compute the softmax loss LS\mathcal{L}_S and Center Loss LC\mathcal{L}_C, and set L=LS+ฮปLC\mathcal{L} = \mathcal{L}_S + \lambda \mathcal{L}_C.
  3. Compute the gradient with respect to the features, โˆ‚Lโˆ‚xi=โˆ‚LSโˆ‚xi+ฮปโ€‰(xiโˆ’cyi)\dfrac{\partial \mathcal{L}}{\partial x_i} = \dfrac{\partial \mathcal{L}_S}{\partial x_i} + \lambda\,(x_i - c_{y_i}). The Center Loss term points in the direction that pulls the feature toward its own class center.
  4. Update the weights WW of the last fully connected layer with the gradient of the softmax loss.
  5. Update each class center cjc_j with the features of that class in the mini-batch, using the formula below.
  6. Update the network weights, such as the convolutional layers, with the gradient from step 3.

The center update is

ฮ”cj=โˆ‘i=1mฮด(yi=j)โ€‰(cjโˆ’xi)1+โˆ‘i=1mฮด(yi=j),cjโ†cjโˆ’ฮฑโ€‰ฮ”cj\Delta c_j = \frac{\sum_{i=1}^{m} \delta(y_i = j)\,(c_j - x_i)}{1 + \sum_{i=1}^{m} \delta(y_i = j)}, \qquad c_j \leftarrow c_j - \alpha\, \Delta c_j

ฮด(yi=j)\delta(y_i = j) is 1 if sample ii belongs to class jj and 0 otherwise. ฮฑโˆˆ[0,1]\alpha \in [0, 1] is the learning rate of the centers. The 1+1 + in the denominator avoids division by zero when the class does not appear in the mini-batch (the sum is 0); in that case the center is not updated.

For example, suppose the center is c=(0.6,ย 0.2)c = (0.6,\ 0.2) and the mini-batch contains two features of this class, (1.0,ย 0.5)(1.0,\ 0.5) and (0.8,ย 0.0)(0.8,\ 0.0). The Center Loss of the first feature is 12{(0.4)2+(0.3)2}=0.125\frac{1}{2}\{(0.4)^2 + (0.3)^2\} = 0.125. The center update is ฮ”c={(โˆ’0.4โˆ’0.2)/3,ย (โˆ’0.3+0.2)/3}โ‰ˆ(โˆ’0.2,ย โˆ’0.033)\Delta c = \{(-0.4 - 0.2)/3,\ (-0.3 + 0.2)/3\} \approx (-0.2,\ -0.033), and with ฮฑ=0.5\alpha = 0.5 the new center is about (0.7,ย 0.217)(0.7,\ 0.217), moving slightly toward the two features.

Ideally, the "center" would be the mean of the class's features over the whole training set. But the features change at every step, so recomputing the mean over all data each time is impractical. The paper moves the centers a little at a time using only the mini-batch and further damps the movement with the learning rate ฮฑ\alpha, so that a few mislabeled samples cannot swing the centers far.

Why combine it with the softmax loss

The key idea of Center Loss is that the softmax loss takes the role of "separating classes" and Center Loss the role of "shrinking each class." Either one alone does not yield discriminative features.

  • Softmax loss alone: The last fully connected layer acts as a linear classifier, and features are separated at the class boundaries. However, a feature is classified correctly anywhere inside its boundary, so large intra-class variation remains. In the paper's 2-D example, the features took a shape radiating out from the origin.
  • Center Loss alone: If all features and centers shrink to 0, the loss becomes almost 0. The paper states that the features and centers then degrade to zero, because nothing separates the classes.
  • Both combined: The softmax loss pushes classes apart, and Center Loss gathers each class near its center. In the paper's 2-D example, the distribution changed with ฮป\lambda, and with a suitable ฮป\lambda the features of each class formed a compact cluster around their center.

As an analogy, the softmax loss "decides each class's section," and Center Loss "moves everyone's seat toward the middle of their section." With sections alone, seats are scattered; with seat-moving alone, everyone ends up in one spot.

The paper also points out differences from Contrastive Loss and Triplet Loss. Those losses build pairs or triplets, so the number of combinations far exceeds the number of samples, convergence tends to be slow and unstable, and selecting the combinations requires extra care. The paper argues that Center Loss can be computed from individual samples and labels alone, just like ordinary classification, and targets the goal of compacting each class more directly.

Experimental results

The paper trained the same CNN (convolutional and locally connected layers, with a 512-dimensional fully connected output) in three ways, changing only the loss, and compared face verification accuracy. The training data had about 0.7 million images of 17,189 people, with ฮป=0.003\lambda = 0.003 and ฮฑ=0.5\alpha = 0.5.

ModelLossLFWYouTube Faces (YTF)
Model ASoftmax loss only97.37%91.1%
Model BSoftmax loss + Contrastive Loss99.10%93.8%
Model CSoftmax loss + Center Loss99.28%94.9%

For reference, FaceNet in the same table (trained on 200 million images) scored 99.63% on LFW and 95.1% on YTF; the Center Loss model comes close with far less training data. Model B converged slowly, requiring 42,000 training iterations compared with 28,000 for models A and C.

On the MegaFace Challenge, which mixes in more than 1 million confusing face images (distractors), in the small training set protocol (fewer than 0.5 million images and fewer than 20,000 people), the results were:

ModelFace identification rate (rank 1)Face verification (at a false accept rate of 10โˆ’610^{-6})
Model A- (softmax loss only)41.863%41.297%
Model B- (+ Contrastive Loss)57.175%69.987%
Model C- (+ Center Loss)65.234%76.516%

These were the best results at the time in the small training set protocol for both identification and verification.

The paper also examined the effect of ฮป\lambda and ฮฑ\alpha. With ฮฑ=0.5\alpha = 0.5 fixed and ฮป\lambda varied from 0 to 0.1, ฮป=0\lambda = 0 (softmax loss only) gave clearly lower LFW accuracy; accuracy rose with a suitable ฮป\lambda and stayed nearly stable over a wide range. With ฮป=0.003\lambda = 0.003 fixed and ฮฑ\alpha varied from 0.01 to 1, accuracy was also nearly stable over a wide range.

The comparisons were made on a single CNN designed by the authors. The comparison with Contrastive Loss is also a result on this architecture, with the loss added to the softmax loss.

Practical considerations

Do not train with Center Loss alone. The features and centers all shrink to 0, so even though the loss becomes small, the features cannot tell the classes apart. Always combine it with a loss that separates classes, such as the softmax loss (cross-entropy), and adjust the weight with ฮป\lambda.

Keep the following points in mind as well.

  • Start with a small ฮป\lambda: The paper used ฮป=0.003\lambda = 0.003 for face recognition. Center Loss scales with the square of the feature magnitude, so the right ฮป\lambda depends on the feature dimension and magnitude. If it is too large, the shrinking force overpowers the force that separates classes.
  • Treat the center update separately from the network weights: In the paper, the centers cjc_j are moved not by gradient descent but by a dedicated update rule with learning rate ฮฑ\alpha. In PyTorch, the centers can also be made an nn.Parameter and updated by the optimizer, but then they behave differently from the paper's rule (which divides by the number of samples of that class in the mini-batch), and the learning rate means something different.
  • The centers take memory: The centers have size number of classes ร— feature dimension. For face recognition in the paper, that was about 17,000 people ร— 512 dimensions.
  • If a mini-batch has few samples of a class, its center moves only slowly: The center of a class absent from the mini-batch is not updated in that step.
  • The centers are not used at test time: They exist only for training; verification and identification use distances between deep features (the output of the first fully connected layer in the paper).
  • PyTorch has no built-in version: A small implementation that follows the paper's formulas is shown below.

Comparison with other methods

The table compares Center Loss with related losses that learn distances between features, from the same viewpoints.

Loss functionData used per termWhat it enforcesHow combinations are builtMain uses
Center Loss (+ softmax loss)One sample and its class labelPull features toward their class center (the softmax loss separates classes)Not neededFeature learning for classification with many classes, such as face recognition
Contrastive LossTwo samples (a pair) and a same/different labelSame: distance 0; different: at least the marginBuild pairsDeciding whether two inputs are the same
Triplet LossThree samples (anchor, positive, negative)Positive closer than negative by the marginBuild and select tripletsFace verification, image retrieval
Supervised ContrastiveThe whole mini-batch and class labelsPull same-class samples together, push different classes apart (compared with softmax)Not needed (needs large batches)Representation learning for labeled classification
Cross-entropy onlyOne sample and its class labelPredict the classNot neededClassification with fixed classes

Rules of thumb for choosing:

  • To compact features with a small addition to ordinary classification training, use Center Loss: No combinations need to be built; it only adds one term to cross-entropy.
  • If there are no class labels, only pairwise relations, use Contrastive Loss: Center Loss keeps class centers, so it needs class labels.
  • If large batches are available, also consider Supervised Contrastive: It pulls same-class samples together and pushes different classes apart directly in a single loss.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F

# Center Loss (Eqs. (2)-(5) of Wen et al. 2016)
class CenterLoss(nn.Module):
    def __init__(self, num_classes, feat_dim, alpha=0.5):
        super().__init__()
        # the centers c_j are not updated by gradients, so keep them as a buffer
        self.register_buffer("centers", torch.zeros(num_classes, feat_dim))
        self.alpha = alpha

    def forward(self, x, y):
        c = self.centers[y]                                    # c_{y_i}
        loss = 0.5 * (x - c).pow(2).sum()                      # L_C = ยฝ ฮฃ โ€–x_i โˆ’ c_{y_i}โ€–ยฒ (โˆ‚L_C/โˆ‚x_i = x_i โˆ’ c_{y_i})
        if self.training:
            self._update_centers(x.detach(), y)
        return loss

    @torch.no_grad()
    def _update_centers(self, x, y):
        num_classes = self.centers.shape[0]
        onehot = F.one_hot(y, num_classes).float()             # ฮด(y_i = j): (m, n)
        count = onehot.sum(0)                                  # number of class-j samples in the mini-batch
        sum_x = onehot.T @ x                                   # ฮฃ ฮด(y_i = j) x_i
        # ฮ”c_j = ฮฃ ฮด(y_i = j)(c_j โˆ’ x_i) / (1 + ฮฃ ฮด(y_i = j))
        delta = (count[:, None] * self.centers - sum_x) / (1 + count[:, None])
        self.centers -= self.alpha * delta                     # c_j โ† c_j โˆ’ ฮฑ ฮ”c_j (ฮ”c_j = 0 for absent classes)

# feature network (the last hidden layer is the feature x) and a fully connected layer for the softmax loss
backbone = nn.Sequential(nn.Flatten(), nn.Linear(28 * 28, 256), nn.PReLU(), nn.Linear(256, 2))   # 2-D features
classifier = nn.Linear(2, 10)
center_loss = CenterLoss(num_classes=10, feat_dim=2, alpha=0.5)
lam = 0.003
opt = torch.optim.SGD(list(backbone.parameters()) + list(classifier.parameters()), lr=0.1, momentum=0.9)

images = torch.randn(128, 1, 28, 28)
labels = torch.randint(0, 10, (128,))
backbone.train(); center_loss.train()
feat = backbone(images)
loss = F.cross_entropy(classifier(feat), labels, reduction="sum") + lam * center_loss(feat, labels)   # L = L_S + ฮป L_C
opt.zero_grad(); loss.backward(); opt.step()

# Test: no centers; verify by the distance between features (cosine distance in the paper)
backbone.eval(); center_loss.eval()
with torch.no_grad():
    f1, f2 = backbone(images[:1]), backbone(images[1:2])
    score = F.cosine_similarity(f1, f2)

FAQ

Q. What value should ฮป be?
A.

The paper used ฮป=0.003\lambda = 0.003 for face recognition (with center learning rate ฮฑ=0.5\alpha = 0.5). In the paper's experiments, ฮป=0\lambda = 0 (softmax loss only) was clearly worse, and around suitable values the accuracy stayed nearly stable over a wide range. The right value depends on the feature dimension and magnitude, so start small and tune on validation data.

Q. Can a model be trained with Center Loss alone?
A.

No. If all features and centers shrink to 0, the loss becomes almost 0, leaving features that cannot tell the classes apart. The paper also states that it must be combined with the softmax loss (cross-entropy).

Q. What is the advantage over Triplet Loss?
A.

No combinations need to be built. Triplet Loss builds triplets, so their number becomes very large and selecting triplets useful for training takes extra care. Center Loss can be computed from individual samples and labels alone, just like ordinary classification. In exchange, it must keep a center for each class, and class labels are required.

References

  1. Y. Wen, K. Zhang, Z. Li, and Y. Qiao, "A Discriminative Feature Learning Approach for Deep Face Recognition," ECCV, 2016.
  2. Y. Wen et al., publicly available PDF of the same paper (author's page)