CosFace: Large Margin Cosine Loss for Deep Face Recognition
- Publication
- CVPR 2018Conference
- First submitted to arXiv
- arXiv:1801.09414
Cite this paper · BibTeX
The citation identifies the linked source version. It cites the original paper and its authors.
@misc{facerecognitioncosface2018,
title = {{CosFace: Large Margin Cosine Loss for Deep Face Recognition}},
author = {Hao Wang and Yitong Wang and Zheng Zhou and Xing Ji and Dihong Gong and Jingchao Zhou and Zhifeng Li and Wei Liu},
year = {2018},
eprint = {1801.09414},
archivePrefix = {arXiv},
url = {https://arxiv.org/abs/1801.09414}
}
The task of face recognition has interested researchers even before the advent of deep learning. As it is one of the few areas with so many real-life applications, it has remained a popular topic over the past decade or more.
Defining the Problem
Face recognition differs from general classification problems due to the following reasons:
- Faces are very similar!
Unlike classification problems on datasets like ImageNet, the challenge in face recognition lies in the fact that photos of the same person can differ significantly due to variations in lighting, angle, expression, and even the camera used.
In general, in this field, we discuss two characteristics of faces:
- High intra-class variation: Photos of the same person can vary greatly due to lighting, angle, expression, age, etc.
- Low inter-class variation: The basic structure of faces is similar, with two eyes, a nose, and a mouth, making different people's photos look quite alike.
Face Recognition System
A typical face recognition system comprises several parts:
- Feature Extractor: Usually a convolutional neural network (CNN) that converts face images into fixed-length feature vectors.
- Training classifier and loss: Identity labels shape the feature space. The classification head is usually removed for deployment, while feature similarity is still computed for recognition.
The feature extractor part is not the focus here as it evolves with the latest backbone networks.
After passing through the feature extractor, we obtain a feature vector , often with 512 dimensions. Earlier work used this length to represent many identities. Discrimination also depends on data and training.
This vector is the key topic in face recognition. Previous research using the Softmax loss function yielded limited model capability, insufficiently distinguishing in marginal cases.
This paper aims to solve this issue.
Solving the Problem
Loss Function
Here, we follow the author's steps to see how the original Softmax loss function is improved.
-
Softmax Loss Function:
Here, is the feature vector, is the output logit for class , is the class of the -th image, is the number of classes, and is the batch size.
is usually the output of a fully connected layer, represented as , where is the weight of the fully connected layer, and is the bias term.
The author sets , so , which can be written as a dot product:
Here, is the angle between and .
Up to this point, nothing has changed; it's just a description of the Softmax loss calculation process.
-
Normalized Softmax Loss (NSL):
Next, the author uses Normalized Softmax Loss (NSL) as a basis for comparison.
By normalizing to 1 using L2 normalization and fixing the length of to , becomes .
NSL removes radial magnitude variation by fixing the norms of the weight vector and the feature vector , leaving only angle variations. Thus, the loss function depends only on the angle:
This focuses feature learning on the angular space, improving feature discrimination.
-
Large Margin Cosine Loss (LMCL):
However, NSL's feature discrimination is still not strong enough. To further improve feature discrimination, the author introduces a cosine margin and naturally incorporates it into Softmax's cosine formulation.
In a binary classification scenario, let be the angle between the learned feature vector and the weight vector of class .
NSL forces for distinguishing between class and .
To build a large margin classifier, we further require:
where is a fixed parameter controlling the cosine margin. Since is smaller than , this constraint is stricter for classification. The two inequalities apply to samples of classes and , respectively; they are not simultaneous requirements for the same sample.
Finally, the author formally defines Large Margin Cosine Loss (LMCL) as:
Under this constraint:
Here, is the number of training samples, is the i-th feature vector corresponding to the ground-truth class , is the weight vector of the j-th class, and is the angle between and .
After understanding these formulas, we can refer to the figure below to grasp the significance of this loss function:
In the figure, the original Softmax loss does not fix the lengths of the weights and features; viewed in cosine-similarity space, the decision regions for the two classes overlap.
With NSL's improvement, we see a boundary between different classes, but this boundary lacks distance, making classification at the intersection unstable.
Finally, with LMCL's enhancement, the boundaries between different classes become clearer. The model, constrained by this boundary during training, finds it easier to distinguish feature vectors in angular space.
There is also the A-Softmax method, an earlier improvement that constrains:
The additional angular penalty is , which varies with and is zero at . This does not erase the entire decision boundary; it means the multiplicative formulation does not provide a fixed angular gap.
Hyperparameter
In learning discriminative features on the hypersphere, the cosine margin is crucial for enhancing feature discrimination.
Under the paper’s idealized class-center assumptions, the scale has the following lower bound; this is not a bound on margin :
where is the number of classes and is the expected minimum posterior probability of the class center.
For a fixed target posterior probability, the analysis suggests increasing as the number of classes grows.
A larger gives fixed-length features enough logit scale during training. How the class count and feature dimension constrain margin is the question for the next section.
Hyperparameter
The figure above is an illustrative experiment with eight identities and two-dimensional features, showing the distributions for , , and .
In this example, the separation between classes in angular space becomes clearer as increases. The two-dimensional distributions should not be read as face-verification accuracy.
Considering the binary classification case, suppose the normalized feature vector is given.
Let denote the normalized weight vector, and denote the angle between and .
For NSL, the decision boundary is defined as , equivalent to the angular bisector of and . This means that under NSL supervision, the model partitions the feature space into two close regions, where features near the boundary are highly ambiguous and can belong to either class.
In contrast, LMCL defines the decision boundary as , where should be much smaller than . This increases inter-class variance while reducing intra-class variance. The maximum angular margin depends on the angle between and .
Specifically, suppose all feature vectors of class exactly overlap with the corresponding weight vector . In this extreme situation, the decision boundary margin reaches its maximum value (i.e., the strict upper bound of the cosine margin).
In general, we assume that all features are well-separated, and there are a total of classes. The theoretical range of cosine margin is:
The Softmax loss attempts to maximize the angle between any two weight vectors from different classes for perfect classification.
Therefore, the optimal solution for the Softmax loss should distribute the weight vectors uniformly on a unit hypersphere.
Based on this assumption, the range of the cosine margin can be inferred as follows:
where is the number of training classes and is the dimension of learned features.
The final expression retains the paper’s to describe a much smaller feasible margin in a crowded feature space; it is not an additional exact, computable upper bound.
These inequalities assume ideally separated class centers. When , the paper explicitly writes that should be much smaller than , rather than reusing the bound for the previous case.
In practice, usually cannot reach the theoretical upper bound because all feature vectors tend to cluster around their corresponding class weight vectors. When is too large, the model fails to converge because the cosine constraint becomes too strict to satisfy. Additionally, an excessively large makes the training process more sensitive to noisy data.
Implementation Details
Theory is just to support the feasibility of a method.
In practice, implementing CosFace is straightforward, and we can quickly write one:
import torch
import torch.nn as nn
class CosFace(nn.Module):
def __init__(self, s=64.0, m=0.35):
super(CosFace, self).__init__()
self.s = s
self.m = m
def forward(self, logits: torch.Tensor, labels: torch.Tensor):
index = torch.where(labels != -1)[0]
target_logit = logits[index, labels[index].view(-1)]
final_target_logit = target_logit - self.m
logits[index, labels[index].view(-1)] = final_target_logit
logits = logits * self.s
return logits
The input logits are normalized feature–weight cosine scores, before softmax. Only the target-class score loses , then all logits are multiplied by .
The adjusted logits can then be used with the standard CrossEntropyLoss.
Discussion
Exploring the Impact of m
-
Experimental Design:
- Varying from 0 to 0.45.
- Training CosFace models on a small dataset (CASIA-WebFace).
- Evaluating performance on LFW and YTF datasets.
-
Experimental Results:
- Models with no margin () performed the worst.
- From to , accuracy increased on both datasets; at , both results were lower than at .
- In this setup, gave the highest LFW and YTF accuracy.
- In this training setup, models failed to converge when exceeded 0.45; this is not a universal threshold.
-
Conclusion:
- The margin effectively enhances the discriminative power of learned features.
- For subsequent experiments, is fixed at 0.35.
Impact of Feature Normalization
-
Experimental Design:
- Comparing CosFace models with and without feature normalization.
- Training on CASIA-WebFace with fixed at 0.35.
- Evaluating performance on LFW, YTF, and Megaface Challenge 1 (MF1) datasets.
-
Experimental Results:
- Models trained without normalization were initially supervised by Softmax loss, followed by LMCL.
- Models using feature normalization consistently outperformed those without normalization across all three datasets.
-
Conclusion:
- Feature normalization removes radial variation in feature norms, making learned features more discriminative in angular space.
- Experiments validate the effectiveness of feature normalization.
Comparison with Other Loss Functions
-
Experimental Design:
- Training models on CASIA-WebFace.
- Using the same 64-layer CNN architecture as described in SphereFace.
- Comparing performance on LFW, YTF, and MF1 datasets.
-
Comparison Settings:
- Strictly following SphereFace's model structure (64-layer ResNet-like CNN) and detailed experimental settings.
- Conducting fair comparisons with other loss functions.
-
Experimental Results:
- On LFW, LMCL scored 99.33%, below A-Softmax's 99.42% and slightly above A-Softmax-NormFea's 99.32%.
- On YTF and MF1, LMCL scored 96.1%, 77.11% Rank-1, and 89.88% verification accuracy, respectively, above the other losses listed in this table under the same training-data and 64-layer CNN settings.
Conclusion
In this paper, the authors proposed a loss function called CosFace, or Large Margin Cosine Loss (LMCL), to improve the discriminative power and classification performance of learned features. They analyzed the limitations of the original Softmax loss and introduced a cosine margin and feature normalization for more effective feature learning.
CosFace offers another way to develop more accurate and efficient models for face recognition and other tasks that need highly discriminative features.