A Discriminative Feature Learning Approach for Deep Face Recognition
- 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}
}
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.

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):
is the deep feature of the -th sample (the output of the last hidden layer), belonging to class ; is the -th column of the weights of the last fully connected layer (the FC layer), and is the bias; is the batch size and 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 is . Take two classes and two-dimensional features, and , and a feature belonging to class 1:
- the logits are 2 and 1, and the probability of class 1 is ;
- stretch along the same direction to , and the logits become 6 and 3, raising the probability to .
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 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 , with the same dimension as the features, and penalize the distance from each feature to its own class center, the paper's Eq. (2):
The gradient with respect to the features is simple, Eq. (3):
Follow the negative gradient and moves toward , pulled harder the farther away it is.
How the centers are updated
The ideal is the average of all features of class , 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 controls how fast the centers learn. The update is Eq. (4):
is 1 when the condition holds and 0 otherwise. Each step does , with .
This is not the gradient of with respect to . 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 be the number of class- samples in the batch and their mean; the numerator is , so:
At each step the center moves part of the way toward the batch's class mean , and how far is set by . This is a kind of moving average.
Plug in numbers. The center is , the batch has two class- features and , and :
- the numerator is , the denominator is , so ;
- the new center is .
The batch mean is , and the center has moved a third of the way.
The in the denominator matters most when 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 , a quarter of the way when . The larger , the closer gets to 1, and the closer the center comes to moving 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):
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:
- Compute and ;
- for each sample, the backpropagated error is ;
- the FC layer weights are updated with the softmax gradient only, since the center loss does not involve ;
- the centers are updated with Eq. (4), ;
- the convolutional parameters are updated by backpropagating the error from step 2, with learning rate .
The centers have their own update rule; they do not go through backpropagation and do not use the network's learning rate.

The same MNIST network, , with raised from 0.001 to 1. Compared with the opening pinwheel, the blades are already noticeably shorter at ; 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 , 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:
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 and with the center starting at , and the updated center is .
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 , and Caffe's softmax loss averages by default too. If both sides average, or both sum, means the same thing; only when one side averages does have to be multiplied or divided by the batch size to convert.
Network and training setup

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 left plot fixes and sweeps . is model A, about 97.4%; add just a tiny bit of center loss () and accuracy jumps to around 99%, then stays between 99.0% and 99.3% all the way to ; only at 0.1 does it drop noticeably.
The right plot fixes and sweeps . From 0.01 to 1, accuracy stays between 98.8% and 99.3%, peaking at 0.6.
Both plots say the same thing; neither nor 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 and .
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.
| Method | Images | LFW | YTF |
|---|---|---|---|
| DeepFace | 4M | 97.35 | 91.4 |
| DeepID2+ (25 nets) | — | 99.47 | 93.2 |
| FaceNet | 200M | 99.63 | 95.1 |
| Deep FR | 2.6M | 98.95 | 97.3 |
| Baidu | 1.3M | 99.13 | — |
| model A (softmax) | 0.7M | 97.37 | 91.1 |
| model B (+contrastive) | 0.7M | 99.10 | 93.8 |
| model C (+center) | 0.7M | 99.28 | 94.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 . A FAR of 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.
| Method | Protocol | Rank-1 | TAR |
|---|---|---|---|
| NTechLAB large | Large | 73.300 | 85.081 |
| Google FaceNet v8 | Large | 70.496 | 86.473 |
| FaceAll Norm 1600 | Large | 64.803 | 67.118 |
| Barebones FR | Small | 59.363 | 59.036 |
| NTechLAB small | Small | 58.218 | 66.366 |
| model A- | Small | 41.863 | 41.297 |
| model B- | Small | 57.175 | 69.987 |
| model C- | Small | 65.234 | 76.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 ; 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_weightis 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 , which worked well with the paper's network and mixed data; while cleaning up the code they found that implementing 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 , 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 ( 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 ( is the batch size; no ), gives the centers their own SGD with learning rate 0.5, and after backprop divides the centers' gradient by so that does not affect how fast the centers update.
The center update then is:
The paper's Eq. (4) times gives each term a coefficient of . 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 and a class appearing twice in the batch, the paper's coefficient is and this implementation's is , 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 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.
| Loss | LFW | YTF | MF Rank-1 | MF TAR |
|---|---|---|---|---|
| softmax | 97.88 | 93.1 | 54.86 | 65.93 |
| +contrastive | 98.78 | 93.5 | 65.22 | 78.87 |
| triplet | 98.70 | 93.4 | 64.80 | 78.32 |
| +center | 99.05 | 94.4 | 65.49 | 80.15 |
| SphereFace | 99.42 | 95.0 | 72.73 | 85.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 , averaged over the batch;
- the denominator of Eq. (4) changes from to (), merely to prevent division by 0;
- the that updates the centers in Algorithm 1 is gone, replaced by the network's learning rate .
Following the expansion above, the center now moves 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 , borrowing the direction directly from the softmax weight and learning only a length (ACL); going further, all classes share a single (ACL-γ). The other relaxes the center from a point to a ball of radius , 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 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 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_weightdepends 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 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 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.