Case study · 2025
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.

- ML Engineer · End to end
- 2025
- Vision AI
- 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
The problem
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.
Overview
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.
Architecture
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
- EDA notebook
Data audit & EDA
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 - Balancing notebook
Balancing & augmentation
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 - GenAI notebook
Generative AI data engine
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) - Training notebook
Transfer learning on Google Colab
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 - XAI & model docs
Evaluation & explainability
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) - Model artifacts
Model registry
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 - API code
Inference API
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) - App code
Flutter mobile app
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
Training evidence
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.
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
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
Transfer learning
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.
- 01
Start pre-trained
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.
- 02
Adapt the input
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.
- 03
Replace the head
Global average pooling gives a 2,048-d feature vector, then a new head: Linear → ReLU → LayerNorm → Dropout → Linear for the six emotions.
- 04
Stage 1 · warm-up
Only the new head trains, so random head weights can't send large gradients back and wreck the pre-trained features.
- 05
Stage 2 · fine-tune
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.
- 06
Compare backbones
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.
Inference flow
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.
- 01
Capture
CameraController streams frames from the front or back camera.
- 02
Detect
Finds faces in real time; only the largest face is sent on, to cut noise.
- 03
Preprocess
Crop, convert to RGB, resize to 224×224 and normalise with the training mean and standard deviation.
- 04
Infer
On-device onnxruntime_flutter session by default; remote API if HF_API_URL is set.
- 05
Explain
Heatmap or region attributions returned with the prediction.
- 06
Display
Emotion, confidence, six probability bars and a cooldown timer so labels don't flicker.
Training recipe
How the model was improved
Each step fixed a specific problem seen in the previous run.
- 01
Classical baseline
LBP, HOG and landmarks with SVM, k-NN and random forests. Too sensitive to pose and lighting.
- 02
Frozen ResNet-50
Only a new head trained. Plateaued early and struggled on fearful and sad.
- 03
More & better data
Augmentation balancing plus quality-gated Stable Diffusion faces for minority emotions.
- 04
Progressive fine-tuning
Head warm-up, then full unfreeze with a low backbone LR so pre-trained features aren't destroyed.
- 05
Regularise
MixUp, label smoothing, weight decay and EMA weights closed the train/val gap.
- 06
Final model
60 epochs, best around epoch 40; early stopping watches macro F1, not accuracy.
Modules & repos
ann-visual-emotion
The full project: README with architecture, data lifecycle, configuration and roadmap. MIT licence and a GitHub Actions CI workflow.
lahirumanulanka/ann-visual-emotionnotebooks/
Four notebooks in pipeline order: EDA, balancing, synthetic generation and transfer-learning training with the XAI toolkit.
lahirumanulanka/ann-visual-emotion/tree/main/notebooksrealtime_app/
Inference server with face cropping, PyTorch/ONNX loading, typed schemas and a simple web template.
lahirumanulanka/ann-visual-emotion/tree/main/realtime_appapp/emotion_detector/
Cross-platform client with screens, services and models folders, the bundled ONNX model and label map, and widget tests.
lahirumanulanka/ann-visual-emotion/tree/main/app/emotion_detectorscripts/
Data prep and ops utilities: face cropping, dataset splitting, grayscale conversion, ONNX export, API benchmarking and GCS upload.
lahirumanulanka/ann-visual-emotion/tree/main/scriptsmodels/
best_model.pth, model.onnx and label_map.json, the single source of truth for every client.
lahirumanulanka/ann-visual-emotion/tree/main/modelsconfigs/
data, model, train and eval configs, so runs are reproducible outside the notebook.
lahirumanulanka/ann-visual-emotion/tree/main/configsHugging Face Space
The hosted emotion detector API, used as the remote fallback by the mobile app.
huggingface.co/spaces/hirumunasinghe/human_face_emotion_detectordeliverables/
The project presentation and screen recordings of real-time and gallery detection.
lahirumanulanka/ann-visual-emotion/tree/main/deliverables
Results
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%
Why transfer learning
- 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
Tools & platforms
- 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
How the test data was built and kept honest
- 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
Generative AI & LLMs in the pipeline
- 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
App testing
- 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
Taking it into agentic AI products
- 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
What I'd do next
- 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