Selected AI Work

Emotion Detector: Real-Time Visual Emotion AI

Vision AI · Transfer learning · GenAI

MSc Data Science · Artificial Neural Networks coursework · Coventry University (2024.2 batch)

An end-to-end emotion AI product: it looks at a face through the phone camera, tells you whether the person is angry, fearful, happy, neutral, sad or surprised, and shows you which parts of the face drove that answer. I built every stage, from cleaning 43K raw images to a generative-AI data pipeline, a ResNet-50 adapted from ImageNet with transfer learning, an explainable API, and a Flutter app.

A glowing wireframe face with a Grad-CAM heat glow over the eyes and smile, beside a phone running the same model on-device
Role
ML Engineer · End to end
Year
2025
Focus
Vision AI
Stack
14 technologies
  • PyTorch
  • timm
  • ResNet-50
  • Transfer learning
  • Google Colab
  • Stable Diffusion
  • Grad-CAM
  • SHAP
  • LIME
  • ONNX Runtime
  • FastAPI
  • Hugging Face
  • Flutter
  • ML Kit
  • 0.812

    Test macro F1 · 81.2% accuracy

  • 83K

    Training images after balancing + GenAI

  • 2,634

    Stable Diffusion faces that passed quality gates

  • 2-stage

    Transfer learning: frozen warm-up → full fine-tune

  • 15–20

    FPS on-device with ONNX Runtime

  • 4

    XAI methods: Grad-CAM, ++, SHAP, LIME

The Flutter app

Screens from the iOS build of the Emotion Detector app, tested on a real iPhone · tap to enlarge

Real-time detection: ML Kit finds the face, the on-device ONNX model labels it, and a cooldown keeps the label from flickering
Photo analysis: pick any image from the gallery and run the same inference pipeline
SHAP explanation: facial regions ranked by how much they pushed the prediction up or down
LIME saliency mask, with Grad-CAM and Grad-CAM++ heatmap toggles under the result

Recognising emotion from faces is useful for wellbeing check-ins, customer-experience research, social robots and human–computer interaction, but real data is messy. In this dataset 'happy' is 30.6% of all images while 'fearful' is only 10.5%, so a naive model learns to guess the common emotions and fails on the rare ones. Hand-crafted features (LBP, HOG, landmark distances with SVM or random forests) only reached about 40–50% accuracy, and a black-box answer like "sad, 24%" is hard for anyone to trust.

The project follows the full ML lifecycle. A data audit verified every one of the 43,756 grayscale images. Targeted augmentation then balanced the classes to 80,370 images, and a Stable Diffusion v1.5 pipeline generated 2,634 extra faces for under-represented emotions. Each generated face had to pass four quality gates before it was allowed into training, which brought the final dataset to 83,004 images, split into 58,102 for training and 12,451 each for validation and test.

Transfer learning is what made the model work. Instead of training a network from scratch on 83K small grayscale faces, I started from a ResNet-50 that had already learned edges, textures and shapes from 1.2M ImageNet photos, and taught it only what is new: how those features map to six emotions. Training ran on Google Colab GPUs. The ImageNet-pre-trained ResNet-50 (with ConvNeXt, EfficientNet-B3 and ViT-B/16 also evaluated) was fine-tuned in two stages. First a new classification head was trained on a frozen backbone, then the whole network was unfrozen with separate learning rates, a cosine schedule, MixUp, label smoothing, mixed precision and an EMA of the weights. The model went from an overfitting baseline to a macro F1 of 0.812 on the untouched test set.

The trained model was exported to ONNX and published to the Hugging Face Hub. It is served two ways: a FastAPI service (also hosted as a Hugging Face Space) that returns the emotion, all six scores and a Grad-CAM heatmap, and a Flutter app that runs the same ONNX model on the phone at 15–20 frames per second, offline, with the API as a fallback.

Explainability is built in, not added later. Grad-CAM and Grad-CAM++ heatmaps show the model looks at the mouth and eyes for 'happy' and the brow for 'angry'. SHAP ranks facial regions by their contribution, and LIME highlights the super-pixels behind a single prediction. All three are visible in the app, so a user or a client can see why the model decided what it did.

System architecture

Eight layers, one repository. Data flows down from raw images to a trained model, and the same ONNX file powers both the cloud API and the phone. Each layer links to its folder on GitHub.

  • Data & infra
  • Service
  • AI agents
  • Channels
  1. Data audit & EDA

    notebooks/01_eda.ipynb
    EDA notebook
    • Raw EmoSet

      43,756 grayscale faces across 6 emotion folders

    • Integrity check

      Every file opened with PIL verify(); corrupt files logged and excluded

    • Metadata scan

      Size, aspect ratio, format (64.6% PNG, 35.4% JPEG) and colour mode per image

    • EDA report

      Class imbalance, pixel geometry (most images 48×48) and sample grids

    clean manifest of image paths + labels
  2. Balancing & augmentation

    notebooks/02_feature_engineering_balancing.ipynb
    Balancing notebook
    • Minority oversampling

      Rotations, flips, colour jitter and random erasing, capped per source image

    • Normalisation

      Resize to a common resolution, grayscale copied to 3 channels for ImageNet backbones

    • Stratified splits

      Seeded train/val/test CSVs and a shared label_map.json

    80,370 balanced images
  3. Generative AI data engine

    notebooks/03_synthetic_gen_ai_generation.ipynb · diffusers
    GenAI notebook
    • Stable Diffusion v1.5

      Prompt templates per emotion, e.g. "a person expressing surprise"

    • Single-face gate

      Rejects images with zero or several faces, so labels stay unambiguous

    • Blur & pHash gates

      Drops blurry outputs and near-duplicates

    • Synthetic cap

      Limits the generated share to keep distribution drift under control

    +2,634 synthetic → 83,004 merged (58,102 / 12,451 / 12,451)
  4. Transfer learning on Google Colab

    notebooks/CNN_with_Transfer_Learning.ipynb · configs/
    Training notebook
    • Backbones

      ResNet-50 (final), ConvNeXt-Base, EfficientNet-B3, ViT-B/16 via timm

    • Stage 1 · warm-up

      Frozen backbone, new head: Linear → ReLU → LayerNorm → Dropout → Linear

    • Stage 2 · fine-tune

      Full unfreeze, LR 1e-4 backbone / 1e-3 head, warm-up + cosine decay

    • Regularisation

      Class weights, label smoothing, MixUp, AMP, gradient clipping, EMA, early stop on macro F1

    best_model.pth
  5. Evaluation & explainability

    pytorch-grad-cam · shap · lime
    XAI & model docs
    • Metrics

      Accuracy, per-class precision/recall/F1, macro F1, confusion matrix

    • Grad-CAM / ++

      Fast heatmaps on ResNet-50's last conv block

    • SHAP

      DeepExplainer with a neutral-face background set, for bias audits

    • LIME

      Super-pixel explanations for individual mistakes

    scripts/export_onnx.py (opset fallback)
  6. Model registry

    models/ · Hugging Face Hub
    Model artifacts
    • PyTorch checkpoint

      best_model.pth with its config snapshot

    • ONNX model

      One portable file for the API and the phone

    • label_map.json

      Index → emotion name, shared by every client

    same model, two runtimes
  7. Inference API

    realtime_app/ · FastAPI · HF Space
    API code
    • face.py

      Detects and crops the face before inference

    • model.py

      Loads the PyTorch or ONNX model and preprocesses with training mean/std

    • main.py · schemas.py

      Typed endpoints returning label, 6 scores and a base64 heatmap

    • Hosted

      Live on Hugging Face Spaces, run locally with uvicorn realtime_app.main:app

    HTTPS · HF_API_URL (optional)
  8. Flutter mobile app

    app/emotion_detector · iOS · Android
    App code
    • Real-time detection

      Camera stream → ML Kit face box → on-device ONNX, 15–20 FPS

    • Photo analysis

      Gallery image through the same pipeline

    • Explanations

      Grad-CAM overlay, SHAP region list, LIME mask

    • Image generation

      Shows the Stable Diffusion augmentation pipeline in action

Straight from the training notebook. These are what I look at to decide whether a model is ready: whether it is still learning, whether it is overfitting, and which classes it confuses.

  1. Fig. 01 · Loss · accuracy · learning rate

    Training curves

    Loss falls steadily for both training and validation and the gap stays small, so overfitting is under control. Macro F1 levels off around epoch 40, which is where early stopping would save compute without losing accuracy.

    • Left: training (red) and validation (blue) loss over 60 epochs
    • Middle: validation macro F1 tracks validation accuracy, so the rare classes are not being sacrificed
    • Right: the head learns 10× faster than the backbone, both warm up then decay on a cosine curve
  2. Fig. 02 · Validation set · 12,451 images

    Per-class report & confusion matrix

    Happy (F1 0.92) and surprised (0.88) are the easiest. The remaining errors are between emotions people also confuse: sad versus neutral, and fearful versus angry.

    • Each class has about 2,075 validation images, so the matrix isn't skewed by imbalance
    • Sad → neutral (163) and neutral → sad (167) is the biggest confusion pair
    • Fearful is the hardest class (F1 0.75), which is why it got the most synthetic data

How transfer learning was applied

Reusing a network pre-trained on ImageNet, then adapting it to faces in two careful stages, so the general visual knowledge is kept and only the emotion-specific part is learned.

  1. 01

    Start pre-trained

    ResNet-50 · ImageNet

    Load weights already trained on 1.2M photos across 1,000 classes. The early layers already detect edges, textures and shapes that faces are made of.

  2. 02

    Adapt the input

    1 → 3 channels

    The grayscale channel is copied into RGB so the original convolution kernels can be reused unchanged, and images are normalised like the pre-training data.

  3. 03

    Replace the head

    1000 → 6 classes

    Global average pooling gives a 2,048-d feature vector, then a new head: Linear → ReLU → LayerNorm → Dropout → Linear for the six emotions.

  4. 04

    Stage 1 · warm-up

    backbone frozen

    Only the new head trains, so random head weights can't send large gradients back and wreck the pre-trained features.

  5. 05

    Stage 2 · fine-tune

    discriminative LRs

    Unfreeze everything: backbone at 1e-4 to nudge features toward faces, head at 1e-3 to keep learning fast, with warm-up and cosine decay.

  6. 06

    Compare backbones

    timm

    Same recipe tried on ConvNeXt-Base, EfficientNet-B3 and ViT-B/16; ResNet-50 was kept as the final backbone for its accuracy and fast on-device inference.

From camera frame to explained prediction

What happens each time the app looks at a face. On-device is the default, so it works offline and no image leaves the phone; the API path is used when a newer model is deployed server-side.

  1. 01

    Capture

    camera plugin

    CameraController streams frames from the front or back camera.

  2. 02

    Detect

    google_mlkit_face_detection

    Finds faces in real time; only the largest face is sent on, to cut noise.

  3. 03

    Preprocess

    Crop, convert to RGB, resize to 224×224 and normalise with the training mean and standard deviation.

  4. 04

    Infer

    ONNX Runtime · or FastAPI

    On-device onnxruntime_flutter session by default; remote API if HF_API_URL is set.

  5. 05

    Explain

    Grad-CAM · SHAP · LIME

    Heatmap or region attributions returned with the prediction.

  6. 06

    Display

    Emotion, confidence, six probability bars and a cooldown timer so labels don't flicker.

How the model was improved

Each step fixed a specific problem seen in the previous run.

  1. 01

    Classical baseline

    ~40–50%

    LBP, HOG and landmarks with SVM, k-NN and random forests. Too sensitive to pose and lighting.

  2. 02

    Frozen ResNet-50

    baseline

    Only a new head trained. Plateaued early and struggled on fearful and sad.

  3. 03

    More & better data

    43.7K → 83K

    Augmentation balancing plus quality-gated Stable Diffusion faces for minority emotions.

  4. 04

    Progressive fine-tuning

    discriminative LRs

    Head warm-up, then full unfreeze with a low backbone LR so pre-trained features aren't destroyed.

  5. 05

    Regularise

    MixUp · EMA

    MixUp, label smoothing, weight decay and EMA weights closed the train/val gap.

  6. 06

    Final model

    macro F1 0.812

    60 epochs, best around epoch 40; early stopping watches macro F1, not accuracy.

Per-class F1 on validation

Balanced data kept every emotion above 0.74.

  • Happy0.92
  • Surprised0.88
  • Angry0.80
  • Neutral0.78
  • Sad0.76
  • Fearful0.75

Accuracy by approach

Same six-class task. Final model: balanced data, GenAI faces and staged fine-tuning.

  • Classic features + SVM~40–50%
  • Early transfer learning~70–80%
  • Final model81.2%

Dataset growth

Images available for training at each stage.

  • Raw, verified43,756
  • + Augmentation80,370
  • + Stable Diffusion83,004

Raw class distribution

Why balancing and synthetic generation were needed.

  • Happy30.6%
  • Neutral18.9%
  • Sad17.2%
  • Angry11.6%
  • Surprised11.3%
  • Fearful10.5%
  • Less data needed: millions of pre-learned visual patterns mean 83K faces is enough to reach macro F1 0.81, where small CNNs trained from scratch overfitted and couldn't match it
  • Faster training: converged faster and needed less hyperparameter search, which matters on time-limited Colab GPU sessions
  • Better on rare emotions: transfer learning improved minority-class recall (fearful, sad), which plain CNNs struggled with
  • Measured, not assumed: hand-crafted features reached ~40–50%, early transfer learning ~70–80%, and staged fine-tuning plus balanced data 81.2%
  • Reusable for clients: the same recipe adapts a pre-trained vision model to a new domain (products, documents, medical images, defects) with a small labelled dataset
  • Google Colab GPU runtimes for training and Stable Diffusion generation, with a CFG block so the same notebook runs locally
  • PyTorch, torchvision and timm for backbones; Hugging Face diffusers for Stable Diffusion v1.5
  • pytorch-grad-cam, SHAP and LIME for explainability
  • ONNX export with opset fallback, ONNX Runtime on mobile, and the Hugging Face Hub and Spaces for hosting
  • FastAPI and Uvicorn for serving, plus a Google Cloud Storage upload script for datasets
  • Flutter with camera, image_picker, google_mlkit_face_detection and onnxruntime_flutter
  • GitHub Actions CI, ruff linting and pytest; Flutter DevTools and the Android Studio profiler for on-device performance
  • Every image was verified with PIL before use, and corrupt files were tracked in a separate exclusion list
  • Seeded, stratified train/validation/test splits saved as CSVs with one shared label map, so every run is evaluated on exactly the same 12,451 test images
  • The test set was kept out of tuning: early stopping and model selection used validation macro F1, and the 0.812 test score is reported separately
  • Macro F1 was the main metric rather than accuracy, so a model can't look good by only getting 'happy' right
  • A face-cropping script (scripts/crop_faces.py) produces the same face-centred framing the app sees after ML Kit detection
  • Real-world checks on top: volunteers used the app in different lighting and camera angles, and scripts/benchmark_api.py measured API latency and throughput
  • Built: Stable Diffusion v1.5 synthetic faces for minority emotions, filtered by single-face detection, blur variance, perceptual-hash dedupe and a synthetic share cap
  • Result: 2,634 new, varied faces with poses and lighting that flips and rotations can't create, improving generalisation without changing the network
  • Designed: an LLM prompt writer (GPT-4 or an open Llama/GPT-2 model via transformers) that varies age, setting and expression in each diffusion prompt for more diverse data
  • Designed: LLM-written explanations that turn a Grad-CAM heatmap into a sentence such as "Smiling mouth and lifted cheeks drove the happy prediction"
  • Analysed the trade-off: diffusion data costs more compute than classic augmentation, and a fine-tuned CNN is far cheaper to run than a general LLM or vision-language model for this task
  • Unit tests for preprocessing, softmax and label mapping
  • Widget tests with mocked camera and face-detection services: Start/Stop Detection, resource release and error states
  • Integration tests covering permissions, tab switching, gallery analysis and remote inference against a local Uvicorn server
  • Profiling CPU, GPU, memory and battery: 15–20 FPS on modern phones, with network latency the main cost on the API path
  • User feedback led to a thicker face box, a prediction cooldown to stop flicker, and accessible text contrast
  • The emotion API is a clean, typed tool, so it plugs straight into an agent framework such as CrewAI, LangGraph or an MCP server as a "read the user's expression" capability
  • Example: a CrewAI crew where a vision agent calls this model, an analysis agent combines the emotion with conversation text, and a response agent adapts tone, the same deterministic-orchestrator pattern I used in my BrokeMe research
  • Cross-modal next step: pair the classifier with a vision-language model so an assistant can both score and describe an expression
  • LLM-assisted labelling to suggest labels for new, unlabelled images and route uncertain ones to a human, cutting manual effort
  • INT8-quantised ONNX build for lower mobile latency and battery use
  • Focal or LDAM loss experiments to lift fearful and sad further
  • CLIP or FaceNet embedding dedupe for synthetic images, on top of perceptual hashing
  • Move the training notebook to scripts/train.py with Hydra configs so CI can retrain and re-evaluate automatically
  • Deletion/insertion tests to measure how faithful each explanation method is, not just how it looks