Machine Learning / Computer Vision

Face Recognitionwith Deep Learning

Learning discriminative face representations with a pretrained ResNet-18 and triplet loss. Transform face images into normalized embedding vectors and compare their similarity for face verification.

ResNet-18Triplet LossLFW Dataset

01 / Overview

Learning a face embedding space

Rather than predicting a fixed identity class, this project learns a feature representation that can be compared across face images.

Face Embeddings

Map each face image into a fixed-dimensional, L2-normalized feature vector.

Metric Learning

Learn to reduce distances between same-identity faces and increase distances between different identities.

Verification

Compare two embeddings with cosine similarity and evaluate the trade-off between true and false positives.

02 / Methodology

From face images to verification

The workflow covers dataset preparation, embedding extraction, triplet-based training, and evaluation.

STEP 01

Dataset Preparation

Load and preprocess RGB face images from the Labeled Faces in the Wild (LFW) dataset.

STEP 02

Embedding Network

Replace the ResNet-18 classification head with a projection layer that generates normalized face embeddings.

STEP 03

Metric Learning

Train with anchor-positive-negative triplets and triplet margin loss to learn discriminative representations.

STEP 04

Face Verification

Compare embeddings using cosine similarity and evaluate pairwise discrimination with ROC and AUC.

03 / Model Architecture

ResNet-18 as an embedding network

The pretrained classification head is replaced with a linear projection layer. L2 normalization constrains each embedding to unit length.

Embedding pipeline

Face Image

RGB input

ResNet-18

Pretrained backbone

Linear Layer

Projection head

L2 Normalize

Unit-length vector

Embedding

Feature representation

Forward pass

def forward(self, x):
    features = self.backbone(x)
    return F.normalize(features, p=2, dim=1)

The output is an embedding vector rather than a probability distribution over known identity classes.

04 / Training

Learning with triplet margin loss

Each training sample contains an anchor, a positive example of the same identity, and a negative example from a different identity.

Triplet objective

d(a, p) + m < d(a, n)

Desired relationship between positive and negative distances.

  • Anchor (a): the reference face.
  • Positive (p): another face image of the same identity.
  • Negative (n): a face image belonging to a different identity.
  • Margin (m): the desired separation between positive and negative distances.

The implemented triplet margin loss penalizes triplets that violate the required margin.

Training configuration

BackboneResNet-18
InitializationImageNet pretrained weights
EmbeddingL2-normalized feature vectors
Loss functionTripletMarginLoss
OptimizerAdamW
Weight decay0.0001
LR schedulerCosineAnnealingLR
CheckpointLowest validation loss

05 / Inference

Comparing face similarity

The trained model converts each face image into a normalized embedding. Cosine similarity then measures the directional similarity between two embeddings.

Face image 1 used for embedding comparison
Face 01
Face image 2 used for embedding comparison
Face 02
Face image 3 used for embedding comparison
Face 03

Example cosine similarity

Example inference outputs from the trained model.

(1, 2)

Highest similarity

0.8614
(1, 3)

Moderate similarity

0.7970
(2, 3)

Lowest similarity

0.5767

Interpretation: Face 1 and Face 2 have the highest similarity (0.8614), followed by Face 1 and Face 3 (0.7970). Face 2 and Face 3 have the lowest similarity (0.5767). These values illustrate relative similarity for this example; they do not establish identity by themselves.

Inference code

with torch.no_grad():
    emb_1 = model(img_1)
    emb_2 = model(img_2)
    emb_3 = model(img_3)

sim_12 = F.cosine_similarity(emb_1, emb_2).item()
sim_13 = F.cosine_similarity(emb_1, emb_3).item()
sim_23 = F.cosine_similarity(emb_2, emb_3).item()

print(f"Similarity (1, 2): {sim_12:.4f}")
print(f"Similarity (1, 3): {sim_13:.4f}")
print(f"Similarity (2, 3): {sim_23:.4f}")

06 / Evaluation

Evaluating the embedding space

The evaluation notebook uses pairwise verification metrics and dimensionality reduction to examine the learned representations.

Face Verification — ROC Curve
ROC curve for face verification using cosine similarity

The ROC curve shows the relationship between the true positive rate and false positive rate across similarity thresholds. AUC summarizes how well the model ranks same-identity pairs above different-identity pairs.

t-SNE Embedding Visualization
t-SNE visualization of face embeddings for the ten most frequent test identities

A two-dimensional projection of the learned embeddings for the ten most frequent identities in the test set. Clusters can help reveal representation structure, but t-SNE is qualitative and does not independently measure verification accuracy.

ROC-AUC

The evaluation procedure samples 3,000 positive pairs and 3,000 negative pairs from the test embeddings and computes cosine similarity and ROC-AUC.

t-SNE

Visualizes the embedding distribution for the ten most frequent test identities to inspect possible identity-level clustering.

07 / Limitations

Understanding the scope

This project is an educational metric learning experiment, not a production-ready identity verification system.

LFW is relatively small compared with modern large-scale face recognition training datasets.

Random triplet sampling may generate easy triplets that contribute little to learning.

Verification performance depends on data splits, preprocessing, identity distribution, and threshold calibration.

Results on LFW do not establish production-level accuracy, robustness, or suitability for KYC systems.

08 / Tech Stack

Tools and technologies

The libraries and frameworks used to build the data, training, inference, and evaluation pipeline.

PythonPyTorchTorchvisionResNet-18Triplet LossMetric Learningscikit-learnNumPyMatplotlib

09 / Project Workflow

Notebook guide

The project is organized into six notebooks, each covering a stage of the machine learning workflow.

01

Data

Load and inspect the LFW dataset.

02

Model

Define the ResNet-18 embedding network.

03

Dataset

Implement triplet sampling and image transformations.

04

Train Triplet

Train the network and save the best checkpoint.

05

Embedding Inference

Generate normalized embeddings from face images.

06

Evaluation

Evaluate verification and visualize embeddings.

Face Recognition with Deep Learning · PyTorch · LFW · Metric Learning