Back to paper library

Center Loss

The Central Idea

Original paper

A Discriminative Feature Learning Approach for Deep Face Recognition

Paper authors

Yandong Wen · Kaipeng Zhang · Zhifeng Li · Yu Qiao

Publication
ECCV 2016Conference
Cite this paper · BibTeX

The citation identifies the linked source version. It cites the original paper and its authors.

@inproceedings{facerecognitioncenterloss2016,
  title = {{A Discriminative Feature Learning Approach for Deep Face Recognition}},
  author = {Yandong Wen and Kaipeng Zhang and Zhifeng Li and Yu Qiao},
  year = {2016},
  booktitle = {ECCV},
  url = {https://doi.org/10.1007/978-3-319-46478-7_31},
  doi = {10.1007/978-3-319-46478-7_31}
}
On this page

Feed MNIST's ten digits into a convolutional network, leave only 2 neurons in the last hidden layer, then plot each image's two numbers on a plane, and you get a pinwheel.

The paper's Fig. 2, two scatter plots. The horizontal axis is the activation of neuron 1, roughly −200 to 100; the vertical axis is neuron 2, roughly −200 to 100. Ten colors stand for the digits 0 to 9. (a) Training set: each class forms a long, thin blade radiating out from the origin, and the ten blades do not overlap; for example, the orange 4 stretches all the way to about −200 on the horizontal axis, and the purple 6 stretches down to about −200. (b) Test set: the blades have the same shape, but near the origin points from several classes are mixed together.
Original Fig. 2, Wen et al., from PDF page 5 of the ECCV 2016 version posted by the first author, scholarly quotation.

This network is trained with softmax alone. On the left are 50,000 training images, on the right 10,000 test images, and the ten colors are the ten digits.

Every class is stretched into a long blade radiating out from the origin. On the training set the ten blades do not overlap, and the final linear classifier can separate them cleanly. The test set is not as pretty, with several classes crowding together near the origin.

Now look inside a single class. The orange 4 stretches from near the origin all the way to about −200, so two points of the same class can be more than 150 apart, while two points of different classes near the origin may be only single digits apart. The classifier does not care; all it asks is which sector each point falls in.

Face recognition does care. The classifier used in training is thrown away wholesale at test time, none of the test people ever appeared in the training set, and all that is left to use is the distance between two features. If two photos of the same person end up farther apart than two strangers, the system gets it wrong.

This paper comes from the Shenzhen Institutes of Advanced Technology, Chinese Academy of Sciences (SIAT). The second author, Kaipeng Zhang, is also the first author of MTCNN, the face detection and alignment tool, and this paper's preprocessing uses exactly MTCNN. The features the authors want have to do two things at once: different classes far apart, the same class packed tight. Their approach is to add a loss term next to softmax that maintains a center for each class and pulls features toward their own center.

Defining the Problem

Separable versus recognizable

The paper first distinguishes two kinds of recognition. Object, scene and action recognition are mostly closed-set ("close-set" in the paper): the test classes all appear in the training set, the classifier's predictions directly determine the score, and softmax was designed for exactly this kind of problem. Face recognition is open-set; you can never collect every person who will be tested in advance, so the classifier is useless at test time and the features can only be used for nearest-neighbor or threshold comparisons.

In that setting it is not enough for features to be merely separable; they also need to be discriminative, compact within a class and far apart between classes. The paper's judgment is that softmax encourages only the former.

First write down the softmax loss, the paper's Eq. (1):

LS=−∑i=1mlog⁡eWyi⊤xi+byi∑j=1neWj⊤xi+bjL_S=-\sum_{i=1}^{m}\log\frac{e^{W_{y_i}^\top x_i+b_{y_i}}}{\sum_{j=1}^{n}e^{W_j^\top x_i+b_j}}

xi∈Rdx_i\in\mathbb R^d is the deep feature of the ii-th sample (the output of the last hidden layer), belonging to class yiy_i; WjW_j is the jj-th column of the weights of the last fully connected layer (the FC layer), and bjb_j is the bias; mm is the batch size and nn is the number of classes. The paper omits the bias in its analysis and says that in practice performance is nearly the same with or without it.

Why does it turn into a pinwheel? The paper only describes the distribution, but you can work out the cause yourself. Omitting the bias, the logit of class jj is Wj⊤xW_j^\top x. Take two classes and two-dimensional features, W1=(1,0)W_1=(1,0) and W2=(0,1)W_2=(0,1), and a feature x=(2,1)x=(2,1) belonging to class 1:

  • the logits are 2 and 1, and the probability of class 1 is e2/(e2+e1)≈0.73e^2/(e^2+e^1)\approx0.73;
  • stretch xx along the same direction to (6,3)(6,3), and the logits become 6 and 3, raising the probability to e6/(e6+e3)≈0.95e^6/(e^6+e^3)\approx0.95.

The direction did not change, yet the loss went down. As long as a feature lands in the right sector, softmax keeps pushing it outward, so points of one class line up into a long ray and the intra-class distance grows along with it.

Existing ways to pull a class together

Adding supervision that "pulls the same class together" on top of softmax already had two routes at the time. Methods in the DeepID2 line add a contrastive loss that compares two faces as a pair; FaceNet uses a triplet loss, with an anchor, a positive and a negative in each group of three.

The problem is the number of combinations. CASIA-WebFace has 490,000 faces, which can form about 1.2×10111.2\times10^{11} pairs, and even more triplets. You cannot compute them all, so you have to pick; pick badly and convergence is slow and unstable, pick well and the computation gets complicated.

The most direct intra-class constraint is to pull each face toward the average of all features in its class. But the features change with every step, so knowing "the average of this class" would mean running the whole training set again at every iteration, which is impossible. The paper says this may be why nobody had used such a loss in CNNs before.

So what is needed is a loss that, like softmax, looks at single samples without forming pairs, yet directly compresses intra-class distance; and the class averages it needs must be estimable on mini-batches.

Solving the Problem

The center loss

The authors give each class a center cj∈Rdc_j\in\mathbb R^d, with the same dimension as the features, and penalize the distance from each feature to its own class center, the paper's Eq. (2):

LC=12∑i=1m∥xi−cyi∥22L_C=\frac{1}{2}\sum_{i=1}^{m}\|x_i-c_{y_i}\|_2^2

The gradient with respect to the features is simple, Eq. (3):

∂LC∂xi=xi−cyi\frac{\partial L_C}{\partial x_i}=x_i-c_{y_i}

Follow the negative gradient and xix_i moves toward cyic_{y_i}, pulled harder the farther away it is.

How the centers are updated

The ideal cjc_j is the average of all features of class jj, but that is exactly the impossible thing mentioned above. The authors make two modifications.

First, use only the mini-batch. Each iteration updates a center using only the features of that class in the current batch; classes that do not appear in the batch keep their centers unchanged for that step.

Second, so that a few mislabeled samples cannot drag a center too far, a scalar α\alpha controls how fast the centers learn. The update is Eq. (4):

Δcj=∑i=1mδ(yi=j) (cj−xi)1+∑i=1mδ(yi=j)\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)}

δ(⋅)\delta(\cdot) is 1 when the condition holds and 0 otherwise. Each step does cj←cj−α Δcjc_j\leftarrow c_j-\alpha\,\Delta c_j, with α∈[0,1]\alpha\in[0,1].

This is not the gradient of LCL_C with respect to cjc_j. The gradient is only the numerator; Eq. (4) further divides it by the number of times the class appears plus 1. Expand it to see what it does: let nj=∑iδ(yi=j)n_j=\sum_i\delta(y_i=j) be the number of class-jj samples in the batch and xˉj\bar x_j their mean; the numerator is nj(cj−xˉj)n_j(c_j-\bar x_j), so:

Δcj=nj1+nj (cj−xˉj)cj−α Δcj=cj+α nj1+nj (xˉj−cj)\begin{aligned} \Delta c_j&=\frac{n_j}{1+n_j}\,(c_j-\bar x_j)\\ c_j-\alpha\,\Delta c_j&=c_j+\alpha\,\frac{n_j}{1+n_j}\,(\bar x_j-c_j) \end{aligned}

At each step the center moves part of the way toward the batch's class mean xˉj\bar x_j, and how far is set by α nj/(1+nj)\alpha\,n_j/(1+n_j). This is a kind of moving average.

Plug in numbers. The center is cj=(0,0)c_j=(0,0), the batch has two class-jj features x1=(2,0)x_1=(2,0) and x2=(0,2)x_2=(0,2), and α=0.5\alpha=0.5:

  • the numerator is (0−2, 0−0)+(0−0, 0−2)=(−2,−2)(0-2,\,0-0)+(0-0,\,0-2)=(-2,-2), the denominator is 1+2=31+2=3, so Δcj=(−23,−23)\Delta c_j=(-\tfrac23,-\tfrac23);
  • the new center is (0,0)−0.5×(−23,−23)=(13,13)(0,0)-0.5\times(-\tfrac23,-\tfrac23)=(\tfrac13,\tfrac13).

The batch mean is (1,1)(1,1), and the center has moved a third of the way.

The 1+1+ in the denominator matters most when njn_j is small. If a class appears only once in the batch and that one image happens to be mislabeled, the center moves toward it by at most α/2\alpha/2, a quarter of the way when α=0.5\alpha=0.5. The larger njn_j, the closer nj/(1+nj)n_j/(1+n_j) gets to 1, and the closer the center comes to moving α\alpha of the way each step.

Training jointly with softmax

The center loss cannot be used on its own. With it alone, the network could shrink all features and all centers to the origin, making the loss 0 while learning nothing. So the paper uses a weighted sum of the two, Eq. (5):

L=LS+λLCL=L_S+\lambda L_C

λ=0\lambda=0 falls back to plain softmax. Softmax pushes different classes apart; the center loss pulls each class tight.

One iteration is the paper's Algorithm 1:

  1. Compute LSL_S and LCL_C;
  2. for each sample, the backpropagated error is ∂LS/∂xi+λ ∂LC/∂xi\partial L_S/\partial x_i+\lambda\,\partial L_C/\partial x_i;
  3. the FC layer weights WW are updated with the softmax gradient only, since the center loss does not involve WW;
  4. the centers are updated with Eq. (4), cj←cj−αΔcjc_j\leftarrow c_j-\alpha\Delta c_j;
  5. the convolutional parameters are updated by backpropagating the error from step 2, with learning rate μt\mu^t.

The centers have their own update rule; they do not go through backpropagation and do not use the network's learning rate.

The paper's Fig. 3, four two-dimensional scatter plots; ten colors stand for the ten MNIST digits, and white dots are the class centers. (a) λ = 0.001: still radial blades, but shorter and more concentrated than with plain softmax; (b) λ = 0.01: each class shrinks into a shorter elliptical cluster, arranged in a ring around the origin; (c) λ = 0.1: each class shrinks into a small cluster, with large empty spaces between clusters; (d) λ = 1: ten very tight small clusters, each labeled with its center c0 to c9.
Original Fig. 3, Wen et al., from PDF page 7 of the ECCV 2016 version posted by the first author, scholarly quotation.

The same MNIST network, α=0.5\alpha=0.5, with λ\lambda raised from 0.001 to 1. Compared with the opening pinwheel, the blades are already noticeably shorter at λ=0.001\lambda=0.001; at 0.01, each class shrinks into an elliptical cluster; at 0.1 and 1, the ten clusters have nearly all shrunk into small dots, with a lot of empty space between them. The white dots are the learned centers, each sitting right in the middle of its cluster. The paper says the features are discriminative over a wide range of λ\lambda, and the face experiments later show the same thing.

In code

The official implementation is a Caffe layer that does exactly Eqs. (2)–(4). Below it is written in PyTorch following Algorithm 1, with the centers stored as a buffer and kept away from the optimizer:

Python
import torch
import torch.nn as nn


class CenterLoss(nn.Module):
    """Center loss of Wen et al., ECCV 2016; centers updated per mini-batch following Algorithm 1."""

    def __init__(self, num_classes, feat_dim, alpha=0.5):
        super().__init__()
        self.alpha = alpha
        centers = torch.empty(num_classes, feat_dim)
        nn.init.xavier_uniform_(centers)                # the official Caffe layer uses xavier init
        self.register_buffer('centers', centers)        # no backprop; updated by Eq. (4)

    def forward(self, x, y):                            # x: [m, d] deep features; y: [m] labels
        c = self.centers[y]                             # the class center of each sample
        loss = 0.5 * (x - c).pow(2).sum()               # Eq. (2)

        if self.training:
            with torch.no_grad():
                delta = torch.zeros_like(self.centers)
                delta.index_add_(0, y, c - x)           # numerator: sum of (c_j − x_i) per class
                n = torch.bincount(y, minlength=len(self.centers))
                delta /= (1 + n).unsqueeze(1)           # denominator: 1 + n_j
                self.centers -= self.alpha * delta      # Algorithm 1: c_j ← c_j − α Δc_j
        return loss

The total loss is ce(logits, y) + lam * center_loss(feat, y). Run it on the numerical example above, two features (2,0)(2,0) and (0,2)(0,2) with the center starting at (0,0)(0,0), and the updated center is (13,13)(\tfrac13,\tfrac13).

There is one detail about scale. Eqs. (1) and (2) both sum over the batch, but the official Caffe layer divides the center loss by the batch size mm, and Caffe's softmax loss averages by default too. If both sides average, or both sum, λ\lambda means the same thing; only when one side averages does λ\lambda have to be multiplied or divided by the batch size to convert.

Network and training setup

The paper's Fig. 4, the CNN architecture for the face experiments. The legend at the top: C is a convolutional layer, P a max-pooling layer, LC a local convolution layer, FC a fully connected layer. Below, from left to right: Input, C, C, P, C, P, LC, P, LC, P, LC, FC; the output of the 4th P feeds both the last LC and, separately, the FC. After the FC the path splits in two, Softmax Loss on top and Center Loss below, added together with weight λ.
Original Fig. 4, Wen et al., from PDF page 8 of the ECCV 2016 version posted by the first author, scholarly quotation.

Both the convolutions and the local convolutions are 3×3 with stride 1, followed by PReLU. The convolutional layers have 128 feature maps and the local convolution layers 256; pooling is 2×2 with stride 2. The weights of a local convolution layer are shared only within a small region, 4×4, 2×2 and 1×1 for the three layers respectively, so the last layer amounts to every position having its own filters. The outputs of the 4th pooling layer and the 3rd local convolution layer are concatenated and fed into the FC layer, which outputs 512 dimensions; that is the feature used for matching, and the center loss is applied there.

Other settings:

  • Preprocessing: MTCNN detects the face and 5 landmarks (two eyes, nose tip, two mouth corners); after a similarity transform the face is cropped to 112×96 RGB, and pixel values have 127.5 subtracted and are divided by 128. Training images where detection fails are discarded; for test images, the landmarks provided by the dataset are used instead.
  • Training data: CASIA-WebFace, CACD2000 and Celebrity+; after removing identities that overlap with the test sets, about 700,000 images of 17,189 people, with horizontal flipping as the only augmentation. Next to FaceNet's 200 million images and DeepFace's 4 million, this is a small training set.
  • Three models: model A uses softmax only, model B softmax plus contrastive loss, model C softmax plus center loss, all with exactly the same architecture.
  • Optimization: Caffe, batch size 256, two TitanX GPUs. A and C start with a learning rate of 0.1, divided by 10 at iterations 16K and 24K and stopped at 28K, about 14 hours; B converges more slowly, so it drops at 24K and 36K and stops at 42K, taking 22 hours.
  • Testing: the FC layer's output is extracted once from the original image and once from the horizontally flipped one, the two are concatenated, PCA is applied, and the cosine distance is computed; identification uses nearest neighbor, verification uses a threshold. All results are from a single model.

Discussion

How finely to tune λ and α

The paper's Fig. 5, two line charts; the vertical axis of both is LFW verification accuracy, 96.5% to 99.5%. (a) α fixed at 0.5, the horizontal axis is λ on a log scale, from 0 to 0.1: about 97.4% at λ = 0, jumping to about 98.95% at 1×10⁻⁴, about 99.25% between 3×10⁻³ and 2×10⁻², about 99.1% at 5×10⁻², dropping to about 98.5% at 0.1. (b) λ fixed at 0.003, the horizontal axis is α, from 0.01 to 1: about 98.8% at 0.01, rising slowly, peaking at about 99.3% at 0.6, about 98.9% at 1.
Original Fig. 5, Wen et al., from PDF page 9 of the ECCV 2016 version posted by the first author, scholarly quotation.

The left plot fixes α=0.5\alpha=0.5 and sweeps λ\lambda. λ=0\lambda=0 is model A, about 97.4%; add just a tiny bit of center loss (10−410^{-4}) and accuracy jumps to around 99%, then stays between 99.0% and 99.3% all the way to 5×10−25\times10^{-2}; only at 0.1 does it drop noticeably.

The right plot fixes λ=0.003\lambda=0.003 and sweeps α\alpha. From 0.01 to 1, accuracy stays between 98.8% and 99.3%, peaking at 0.6.

Both plots say the same thing; neither λ\lambda nor α\alpha needs fine tuning, and the gap between having center loss and not having it is far larger than the gaps between parameter settings. The face experiments that follow fix λ=0.003\lambda=0.003 and α=0.5\alpha=0.5.

LFW and YTF

LFW uses 6,000 photo pairs for 1:1 verification and reports the mean accuracy over 10 folds; YTF uses 5,000 video pairs and checks whether two clips show the same person. Both follow the "unrestricted with labeled outside data" protocol, which allows training on external labeled data. Nobody in the training data overlaps with LFW or YTF.

MethodImagesLFWYTF
DeepFace4M97.3591.4
DeepID2+ (25 nets)—99.4793.2
FaceNet200M99.6395.1
Deep FR2.6M98.9597.3
Baidu1.3M99.13—
model A (softmax)0.7M97.3791.1
model B (+contrastive)0.7M99.1093.8
model C (+center)0.7M99.2894.9

Compiled from Table 2 of the paper, in %.

Same network, same data, only the supervision signal changes. From A to C, the LFW error rate drops from 2.63% to 0.72%, down by more than 70%; YTF rises from 91.1% to 94.9%. B, with the contrastive loss, also improves a lot, but loses to C on both datasets, and B needs half again as many iterations and 8 more hours.

Against others, C reaches 99.28% with 700,000 images, behind only DeepID2+'s 25-network ensemble and FaceNet's 200 million images. On YTF, its 94.9% trails FaceNet's 95.1% and also Deep FR's 97.3%.

MegaFace: a million strangers

LFW had passed 99%, with differences down to the decimals. MegaFace was the new exam of the time, scaling the problem up to a million.

Its gallery (the list matched against) has more than 1 million photos of 690,000 people, taken from Flickr; its probes (the photos used as queries) come in two sets, FaceScrub (530 celebrities, 100,000 photos) and the cross-age FGNet. There are two ways to be tested:

  • Identification (1:N): take a probe photo and search the gallery, which contains at least one photo of the same person, the rest all distractors. The Rank-1 identification rate is the share of probes for which the correct photo ranks first, with distractors increased from 10 to 1 million.
  • Face verification (1:1): 4 billion different-person pairs can be formed between probes and gallery, and the TAR is reported at a FAR of 10−610^{-6}. A FAR of 10−610^{-6} means only 4,000 of these 4 billion pairs may be falsely accepted; TAR is the share of same-person pairs that pass at that threshold.

MegaFace has two protocols depending on training-data size. The small protocol limits training data to fewer than 500,000 images and fewer than 20,000 people. The authors cut their training data to 490,000 images, kept the number of people at 17,189, dropped photos that overlap with FaceScrub, and retrained models A-, B- and C- with the same parameters, testing only Set 1 of the three galleries.

MethodProtocolRank-1TAR
NTechLAB largeLarge73.30085.081
Google FaceNet v8Large70.49686.473
FaceAll Norm 1600Large64.80367.118
Barebones FRSmall59.36359.036
NTechLAB smallSmall58.21866.366
model A-Small41.86341.297
model B-Small57.17569.987
model C-Small65.23476.516

Rank-1 compiled from Table 3 of the paper, the identification rate with 1 million distractors; TAR compiled from Table 4 of the paper, the verification rate at a FAR of 10−610^{-6}; in %.

On LFW, A and C differ by less than 2 percentage points; with a million distractors, A-'s Rank-1 drops to just 41.9% while C- holds 65.2%, a gap of 23 percentage points, and the verification rates differ by 35 percentage points. Softmax-only features show no problem on a small exam; add enough distractors and the cost of loose classes shows.

Within the small protocol, C- beats the best of the other teams by 5.87 (identification) and 10.15 (verification) percentage points, and also beats both of Beijing FaceAll's large-protocol models. The top two on the table are still NTechLAB and Google under the large protocol, and the authors add a line in the text that their private training sets were 18 million and 500 million images respectively, against C-'s 490,000.

How the official code differs from the paper

The authors released ydwen/caffe-face in October 2016; the README says it trains on CASIA-WebFace and that a single model should reach about 99% on LFW. Compared with the paper, several things differ:

  • Network: the paper uses a network with three local convolution layers; the repo has a 28-layer residual network, with the same 512-dimensional FC output.
  • Data: the paper uses the 700,000-image mixed dataset; the repo's example uses CASIA-WebFace, with 10,572 classes in the last layer.
  • λ: 0.003 in the paper; the prototxt's loss_weight is 0.008.
  • α: 0.5 in the paper; the repo computes the center update following Eq. (4) but leaves the actual update to Caffe's optimizer, so the center learning rate is just the network's 0.1 (later dropping to 0.01 and 0.001), with momentum 0.9 and weight decay on top.

The repo has issues turned off, so discussion gathered under one PR. PR #1 started as a user speeding up the center layer's backward pass: on a dataset with 750,000 classes, the center layer's backward pass went from 3,332 milliseconds to 5.4 milliseconds. It later became the place where everyone reported their reproduction results, piling up more than a hundred comments.

Yandong Wen explained the reasons in a reply on October 27, 2016. At first they updated with the paper's α\alpha, which worked well with the paper's network and mixed data; while cleaning up the code they found that implementing α\alpha separately in Caffe was awkward, even more so with multiple GPUs, so they switched to Caffe's learning rate and weight decay, with about the same results. The local convolution layers were not implemented elegantly and cost more time and space (the 6-layer deepidnet took about 14 hours and 200M, the 28-layer residual network about 8 hours and 100M), so they released the residual network, which performed better. As for λ\lambda, it depends on the number of classes: the more classes, the smaller loss_weight should be.

Reports from people training with the repo mostly landed between 98.4% and 99.05%. With CASIA-WebFace and the official settings, people got 98.47% and 98.9%; Feng Wang (happynear on GitHub) reached 99.05% using the evaluation trick the author suggested. Computing directly from the LFW features the author released gives about 98.98% without PCA, and reports with PCA range from 99.02% to nearly 99.27%, depending on how the PCA was trained. In June 2018 someone opened PR #4, saying most people could not reproduce 99.28%, not even with the author's features, and asking the author to release the evaluation code. (PR #4, opened in 2018, still has 0 comments.)

In the same thread, happynear pointed out in December 2016 that the centers should not get weight decay: most classes have an update of 0 in any given batch, so decay would just keep pushing the centers toward the origin. In February 2017 someone asked why training pulls toward the centers with Euclidean distance while testing uses cosine. happynear answered that the two are equivalent once features are normalized (2−2cos⁡θ2-2\cos\theta is exactly the squared Euclidean distance), and that they were writing a paper on this. Two months later, that paper was NormFace.

The denominator in the PyTorch implementation

The most widely used version on PyTorch is KaiyangZhou/pytorch-center-loss (nearly a thousand stars), which deep-person-reid, the person re-identification library, also uses. It makes the centers an nn.Parameter, takes the loss as ∑i∥xi−cyi∥2/B\sum_i\|x_i-c_{y_i}\|^2/B (BB is the batch size; no 12\tfrac12), gives the centers their own SGD with learning rate 0.5, and after backprop divides the centers' gradient by λ\lambda so that λ\lambda does not affect how fast the centers update.

The center update then is:

cj←cj−0.5⋅2B∑i: yi=j(cj−xi)=cj−1B∑i: yi=j(cj−xi)\begin{aligned} c_j&\leftarrow c_j-0.5\cdot\frac{2}{B}\sum_{i:\,y_i=j}(c_j-x_i)\\ &=c_j-\frac{1}{B}\sum_{i:\,y_i=j}(c_j-x_i) \end{aligned}

The paper's Eq. (4) times α\alpha gives each term a coefficient of α/(1+nj)\alpha/(1+n_j). The denominators differ, one being the size of the whole batch and the other the number of samples of this class in the batch plus 1. With B=128B=128 and a class appearing twice in the batch, the paper's coefficient is 0.5/3≈0.1670.5/3\approx0.167 and this implementation's is 1/128≈0.00781/128\approx0.0078, a center step about 21 times smaller.

In April 2018 someone asked in issue #2 whether this was equivalent to the paper; the repo author replied "It is equivalent to the paper.", and others later pointed out one after another that the paper averages by the number of samples of that class in the batch. (One denominator is 128, the other is 3.) When you use this code, lr_cent effectively absorbs both α\alpha and this denominator, so you have to retune it yourself.

Center loss in other people's tables

The next year, SphereFace retrained softmax, contrastive loss, triplet loss and center loss all in the same 64-layer network on the same CASIA-WebFace (490,000 images). SphereFace's second author is none other than Yandong Wen.

LossLFWYTFMF Rank-1MF TAR
softmax97.8893.154.8665.93
+contrastive98.7893.565.2278.87
triplet98.7093.464.8078.32
+center99.0594.465.4980.15
SphereFace99.4295.072.7385.56

Compiled from the LFW/YTF and MegaFace comparison tables of the SphereFace paper (arXiv 1704.08063v4), in %; MF is the MegaFace small protocol.

On someone else's network and data, center loss's MegaFace Rank-1 is 65.49%, nearly identical to the original paper's C- at 65.23%, and the gain over softmax reproduces too. SphereFace, which moves the margin to the angle, simply goes another 7 percentage points higher. CosFace's comparison table reuses these numbers and puts LMCL in the last row, with a Rank-1 of 77.11%.

What the journal version changed

In January 2019 the authors published an extended version in IJCV, "A Comprehensive Study on Center Loss for Deep Face Recognition." The center update was rewritten to follow the code:

  • the loss becomes 12m∑∥xi−cyi∥2\frac{1}{2m}\sum\|x_i-c_{y_i}\|^2, averaged over the batch;
  • the denominator of Eq. (4) changes from 1+nj1+n_j to ϵ+nj\epsilon+n_j (ϵ=10−5\epsilon=10^{-5}), merely to prevent division by 0;
  • the α\alpha that updates the centers in Algorithm 1 is gone, replaced by the network's learning rate μt\mu^t.

Following the expansion above, the center now moves μt\mu^t of the way toward the batch mean each step, with the step size left to the network's learning rate, just as in the official Caffe code.

The journal version also adds two extensions. One is parameter sharing: write the center as cj=γjwjc_j=\gamma_j w_j, borrowing the direction directly from the softmax weight wjw_j and learning only a length γj\gamma_j (ACL); going further, all classes share a single γ\gamma (ACL-γ). The other relaxes the center from a point to a ball of radius ρ\rho, so features inside the ball are no longer penalized.

The experiments switch to VGGFace2 (2.87 million images, 7,994 people) and a 20-layer residual network, with λ\lambda fixed at 0.01. Two tables are useful for understanding where the original center loss stands.

The first compares the losses under the same conditions. On LFW's 6,000 pairs, the original center loss scores 99.35% and SphereFace 99.42%; on the harder BLUFR open-set identification (DIR, rank-1, FAR 1%), center loss scores 79.32%, ACL-γ 83.61% and SphereFace 91.34%. The authors' wording is that all three are "marginally inferior than SphereFace." (83.61 versus 91.34.)

The second is 1:1 verification on IJB-A. At FAR 0.1 and 0.01, adding center loss beats plain softmax; at FAR 0.001, softmax scores 81.43% while softmax plus the original center loss gets only 78.51%, 2.9 percentage points lower, and it takes ACL-γ to climb back to 89.07%. At the strictest threshold, the original version is not reliable.

In the journal version, the best combination on BLUFR, YTF, and IJB-A at FAR 0.001 and 0.01 is always SphereFace plus ACL-γ.

Center loss in person re-identification

This loss later became common in person re-identification as well. In 2019, "Bag of Tricks and A Strong Baseline for Deep Person Re-identification" put it into a widely used baseline with a weight of 0.0005, trained together with a triplet loss and a classification loss. On a model that already has BNNeck and other tricks, adding center loss moves Market1501's rank-1 from 94.1% to 94.5% and DukeMTMC's from 86.2% to 86.4%; in the cross-dataset experiments, the authors say it has little effect.

Limitations

  • The center matrix is as big as the FC layer. The centers form an n×dn\times d matrix that grows with the number of classes. For Glint360K's 360,000 classes at 512 dimensions in float32, the centers alone take over 700 MB of extra GPU memory (this note's estimate), not counting the FC layer itself.
  • Most centers do not move at any given step. CASIA-WebFace has over ten thousand classes; with a batch of 256, at most 256 centers are updated per step and more than 97% stay where they are. With many classes and few photos per class, the center estimates lag behind the features.
  • Training and testing use different distances. The center loss pulls on unnormalized Euclidean distance, while testing uses PCA plus cosine; this mismatch was later handled by the normalization approach that runs from NormFace to ArcFace.
  • λ has to be tuned to the data. The authors themselves say loss_weight depends on the number of classes, smaller with more classes; the community has also reported that on large datasets 0.008 kept the softmax loss from going down, and it took 10−410^{-4} to get training going.

Conclusion

Center loss maintains a center for each class, updates it with a mini-batch moving average, and pulls features toward the centers jointly with softmax. With the same network and the same 700,000-image dataset, LFW goes from 97.37% to 99.28% and the MegaFace small-protocol Rank-1 from 41.9% to 65.2%; the gain reproduces on other people's networks too, though the angular margins that came later went further.

To use it in your own project, first decide which rule the centers update by. Following the paper, the centers bypass the optimizer and move α nj/(1+nj)\alpha\,n_j/(1+n_j) of the way toward the batch mean each step; with the off-the-shelf PyTorch version, the center learning rate has to be retuned, and keep weight decay off the centers. If testing uses cosine distance, it is best to normalize the features during training too.

A year later, SphereFace, with Wen as second author, moved the margin onto the angle; in the experiment tables of the journal version, more than two years on, the best combination on most metrics was SphereFace plus an improved center loss.