Face Detection & Recognition
Module: Computer Vision | Difficulty: Intermediate
Face Detection Pipeline
MTCNN Architecture
Three-stage cascade:
- P-Net: Proposal network for candidate windows
- R-Net: Refine network to reject false positives
- O-Net: Output network for facial landmarks
FaceNet Loss
where is anchor, is positive, is negative, is margin.
ArcFace Loss
Face Verification
import torch
import torch.nn as nn
class ArcFaceLoss(nn.Module):
def __init__(self, embedding_dim, num_classes, s=30.0, m=0.50):
super().__init__()
self.s = s
self.m = m
self.weight = nn.Parameter(torch.randn(num_classes, embedding_dim))
nn.init.xavier_uniform_(self.weight)
def forward(self, embeddings, labels):
cos_theta = nn.functional.linear(
nn.functional.normalize(embeddings),
nn.functional.normalize(self.weight)
)
theta = torch.acos(cos_theta.clamp(-1 + 1e-7, 1 - 1e-7))
target_logits = torch.cos(theta + self.m)
one_hot = torch.zeros_like(cos_theta)
one_hot.scatter_(1, labels.view(-1, 1), 1.0)
logits = one_hot * target_logits + (1 - one_hot) * cos_theta
logits *= self.s
return nn.functional.cross_entropy(logits, labels)
Key Takeaways
- MTCNN provides fast multi-scale face detection
- ArcFace angular margin improves discriminative power
- Anti-spoofing is critical for real-world deployment