CoolFace
Apppublic

shivams496/Pulsewatcher

sourceHugging Faceupdated 4mo agoView on Hugging Face
0likes
App README

๐Ÿซ€ PulseWatcher โ€” ECG Anomaly Detection System

<p align="center"> <img src="https://img.shields.io/badge/Model-LSTM%20Autoencoder-00d4ff?style=for-the-badge&logo=pytorch&logoColor=white"/> <img src="https://img.shields.io/badge/Dataset-MIT--BIH%20Arrhythmia-00e87a?style=for-the-badge"/> <img src="https://img.shields.io/badge/Framework-PyTorch-ee4c2c?style=for-the-badge&logo=pytorch&logoColor=white"/> <img src="https://img.shields.io/badge/Dashboard-Streamlit-ff4b4b?style=for-the-badge&logo=streamlit&logoColor=white"/> <img src="https://img.shields.io/badge/Deployed-Hugging%20Face-ffb020?style=for-the-badge&logo=huggingface&logoColor=white"/> <img src="https://img.shields.io/badge/Type-Unsupervised-b060ff?style=for-the-badge"/> </p>

<p align="center"> Real-time ECG anomaly detection using an LSTM Autoencoder trained <strong>exclusively on normal heartbeats</strong>.<br/> Anomalies are detected through reconstruction error โ€” no anomaly labels required during training. </p>

<p align="center"> <a href="https://huggingface.co/spaces/shivams496/Pulsewatcher"> <img src="https://img.shields.io/badge/๐ŸŒ%20Live%20Demo-Hugging%20Face%20Spaces-yellow?style=for-the-badge"/> </a> </p>


How It Works

MIT-BIH Dataset (PhysioNet)
        โ”‚
        โ–ผ
Beat Segmentation + Normalisation
  (187 timesteps, min-max normalised per beat)
        โ”‚
        โ–ผ
LSTM Encoder โ†’ Latent Space (64 units) โ†’ LSTM Decoder
        โ”‚
        โ–ผ
Reconstruction Error (MSE per timestep)
        โ”‚
        โ–ผ
Threshold (82nd percentile of normal train errors)
        โ”‚
   โ”Œโ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”
   โ–ผ         โ–ผ
NORMAL    ANOMALY

Key insight: The model never sees anomalous beats during training. It learns only what normal looks like. When an anomalous beat is fed in, reconstruction fails โ€” the error spike is the detection signal.


Results

Threshold Sensitivity Analysis

MetricBefore (95th pct)After (82nd pct)Change
Precision95.21%89.82%-5.4%
Recall44.64%71.35%+26.7%
F1 Score60.79%79.53%+18.7%
ROC-AUC0.86780.8678same

Sweeping to the 82nd percentile yields Precision = 89%, Recall = 71%, F1 = 0.795 โ€” a 24% improvement in anomaly detection at the cost of 7% more false positives. The optimal threshold is a clinical decision, not a model decision.

Model Comparison (same test set, same threshold logic)

ModelPrecisionRecallF1AUC
LSTM Autoencoder (ours)89.82%71.35%79.53%0.8678
1D CNN Autoencoder73.77%28.35%40.96%0.6737

LSTM wins across every metric. ECG beats are temporal sequences with known structure (Pโ†’QRSโ†’T) โ€” LSTM's sequential memory is a natural fit. CNN treats the signal as a spatial pattern and loses the temporal ordering that makes arrhythmias detectable.


Dashboard Features

FeatureDescription
Live ECG SimulationBeat-by-beat streaming with st.empty() loop. Anomaly score bar updates in real time.
Explainability HeatmapECG waveform colour-coded by reconstruction error: cyan (low) โ†’ amber (mid) โ†’ crimson (high).
CSV / ECG UploadUpload any ECG signal. Auto-normalises, resamples to 187 pts, runs inference instantly.
PDF ReportOne-click dark-themed clinical PDF: beat class, error, anomaly score, top-5 error timesteps.
Dynamic MetricsAll metrics loaded live from models/metrics.json โ€” no hardcoded strings.

Model Details

  • โ€”Architecture: LSTM Autoencoder (encoder-decoder)
  • โ€”Hidden units: 64
  • โ€”Parameters: ~110K
  • โ€”Input shape: (N, 187, 1)
  • โ€”Training: Normal beats only (unsupervised)
  • โ€”Inference: <5ms per beat on CPU

Why unsupervised? In clinical settings, labelled anomaly data is rare and expensive. Training on normal beats only allows the model to generalise to anomaly types it has never seen, as long as they deviate from normal morphology.


Project Structure

ecg-anomaly-detection/
โ”œโ”€โ”€ dashboard/
โ”‚   โ””โ”€โ”€ app.py              # Streamlit dashboard (all features)
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ model.py            # LSTM Autoencoder architecture
โ”‚   โ”œโ”€โ”€ train.py            # Training loop
โ”‚   โ”œโ”€โ”€ evaluate.py         # Threshold sweep + metrics
โ”‚   โ”œโ”€โ”€ cnn_autoencoder.py  # CNN baseline model
โ”‚   โ””โ”€โ”€ benchmark.py        # Model comparison script
โ”œโ”€โ”€ models/
โ”‚   โ”œโ”€โ”€ lstm_autoencoder.pt # Trained LSTM weights
โ”‚   โ”œโ”€โ”€ threshold.npy       # Optimal threshold (82nd percentile)
โ”‚   โ”œโ”€โ”€ train_errors.npy    # Training reconstruction errors
โ”‚   โ”œโ”€โ”€ metrics.json        # Live metrics for dashboard
โ”‚   โ””โ”€โ”€ benchmark.json      # LSTM vs CNN comparison results
โ”œโ”€โ”€ requirements.txt
โ””โ”€โ”€ README.md

Setup

bash
git clone https://github.com/shivams496/ecg-anomaly-detection
cd ecg-anomaly-detection
pip install -r requirements.txt

Start the dashboard:

bash
streamlit run dashboard/app.py

Run threshold sweep (optional โ€” results already saved):

bash
python -m src.evaluate

Run model benchmark:

bash
python -m src.benchmark

Dataset

MIT-BIH Arrhythmia Dataset via PhysioNet.

SplitNormalAnomaly
Train59,816โ€”
Test14,95533,308

48 recordings ยท 30 min each ยท 360 Hz ยท 47 patients ยท 15+ arrhythmia classes


Known Limitations

  1. 1.Single-beat classification only โ€” rhythm-level disorders (e.g. AFib) require inter-beat interval (RR) analysis, not just beat morphology.
  2. 2.MIT-BIH distribution โ€” trained on Holter monitor recordings. Signals from different device types or electrode placements may need threshold recalibration.
  3. 3.Unusual-but-benign beats โ€” patients with non-standard baseline ECGs may generate higher reconstruction errors without true pathology.
  4. 4.Not FDA/CE approved โ€” for research and educational use only.

Future Work

  • โ€”[ ] RR interval analysis for rhythm-level anomaly detection (AFib, heart block)
  • โ€”[ ] Multi-lead ECG support (currently single-lead)
  • โ€”[ ] Patient-specific threshold calibration
  • โ€”[ ] HL7/FHIR integration for hospital data pipelines
  • โ€”[ ] Transformer autoencoder ablation study

Interview Q&A

"Why LSTM over Transformer?" MIT-BIH beats are 187 timesteps โ€” short structured sequences with known temporal order (Pโ†’QRSโ†’T). Transformers excel at long sequences with long-range dependencies. LSTM captures within-beat temporal structure naturally. The benchmark confirms it: LSTM F1 79% vs CNN F1 41%.

"Why is recall not higher?" The threshold is a clinical tuning parameter. At the 95th percentile, precision is 95% but recall is 44%. At the 82nd percentile, precision drops to 89% but recall rises to 71% (+27%). The right operating point depends on the clinical context โ€” a general ward might prefer high precision; a cardiac ICU might prefer high recall.

"How would this run in a hospital?" <5ms inference on CPU. Dockerised. Threshold adjustable per cohort without retraining. The Hugging Face deployment proves it runs without a GPU.


Tech Stack

Python ยท PyTorch ยท Streamlit ยท NumPy ยท SciPy ยท scikit-learn ยท ReportLab ยท Pandas ยท WFDB


B.Tech Final Year Project โ€” ECG Anomaly Detection