ECG Analysis Studio
Educational project · Not a medical device · All processing runs offlineOffline single-lead ECG arrhythmia analysis: 0.5–40 Hz Butterworth filtering, Pan–Tompkins R-peaks, 57 per-beat features, and a 50-tree MIT-BIH Random Forest.
Interactive ECG Analysis Workspace
src/portable.py parity · 100% browser-sideLoading annotated records…
Requires at least 10 seconds of signal (≥ 3,600 samples at 360 Hz), matching the Streamlit & Android apps.
Beat Morphology Inspector (200 samples)
Window: −90..+110 samples around R=90 (median-centered). Shaded R±40 zone & dashed ±0.3·max|x| lines illustrate QRS width; cyan dots show the 40 shape samples (every 5th point).
AI Classification & Tree Consensus
57 Beat Features (Exact Model Inputs)
Class Distribution
R-R Interval Tachogram
Click any point to select & center that beat. Dashed line = recording median R-R.
Beat & Arrhythmia Navigator
| # | Time (s) | Prev RR | Pred | Truth | p(pred) | Match |
|---|---|---|---|---|---|---|
| Loading… | ||||||
DSP Pipeline & Live Filter Frequency Response
Every filter coefficient in ecg-config.json is executed directly with Direct Form II Transposed biquad loops and odd-extension zero-phase filtfilt (padlen = 720) — zero scipy dependency at runtime, verified to 5e-10 mV against Python.
Exact Second-Order Sections (ecg-config.json)
57-Feature Extraction Specification
Features are extracted from each 200-sample beat window [p − 90, p + 110) after subtracting the beat's own median, paired with local and recording-median R-R timing. Feature ordering [0..56] is strictly frozen to match the Random Forest split indices.
Selected Beat — 40-Point Normalized Shape Vector (shape_0 .. shape_39)
| Indices | Group | Feature(s) | Exact Formula (src/portable.py) | Units |
|---|---|---|---|---|
| 0 | R-R Timing | prev_rr | peaks[k] - peaks[k - 1] | samples |
| 1 | R-R Timing | next_rr | peaks[k + 1] - peaks[k] | samples |
| 2 | R-R Timing | prev/next | prev_rr / next_rr | ratio |
| 3 | R-R Timing | prev/med_rr | prev_rr / median(prev_rr) | ratio |
| 4 | R-R Timing | next/med_rr | next_rr / median(prev_rr) | ratio |
| 5 | Morphology | amp_r | x[90] (after x = beat - median(beat)) | mV |
| 6–8 | Morphology | peak, trough, p2p | max(x), min(x), peak - trough | mV |
| 9–10 | Morphology | t_peak, t_trough | argmax(x) - 90, argmin(x) - 90 | samples |
| 11 | Morphology | width | count(|x[50:130]| > 0.3 * max(|x|)) | samples |
| 12–14 | Morphology | energy, area, sd | sum(x²), sum(|x|), sqrt(mean((x - mean)²)) | mV² / mV |
| 15–16 | Morphology | skew, kurtosis | m3 / m2^1.5, m4 / m2^2 - 3 (biased) | dimless |
| 17–56 | Beat Shape | shape_0 .. shape_39 | x[::5] / (p2p + 1e-8) (every 5th sample) | normalized |
Model Architecture, Published Evaluation & Honest Limits
Trained strictly on DS1 (22 patients) and evaluated end-to-end from raw signals on DS2 (22 completely unseen patients). No patient overlaps between training and testing.
- Model
RandomForestClassifier· 50 trees ·min_samples_leaf = 5· 36,436 nodes · 1.28 MB JSON (scikit-learn 1.6.1)- Imbalance handling
compute_sample_weight("balanced", y)during fit + per-class decision weights[1.0, 2.0, 1.0, 0.0]tuned via 5-fold patient-grouped CV on DS1- R-peak performance
- 49,712 annotated · 49,680 detected · 49,564 matched · sensitivity 99.7% · positive predictivity 99.8% · median offset 0 samples (5th/95th: −1/+1)
- End-to-end headline
- Accuracy 93.3% (0.933) · Macro F1 (N, S, V) 0.688 over 49,558 matched beats (annotation-aligned 49,661 beats: Macro F1 0.690)
| Class | Precision | Recall | F1 | Test Beats | Share |
|---|---|---|---|---|---|
| N Normal | 0.958 | 0.972 | 0.965 | 44,167 | 89.1% |
| S Supraventricular | 0.201 | 0.158 | 0.177 | 1,825 | 3.7% |
| V Ventricular | 0.901 | 0.945 | 0.923 | 3,183 | 6.4% |
| F Fusion (weight 0) | — | — | — | 383 | 0.8% |
Model Shrinkage & Size Budget Study (09_shrink_model.ipynb)
| Trees | Min Leaf | Total Nodes | CV Macro F1 (N,S,V) | Decision Weights | Status |
|---|---|---|---|---|---|
| 200 | 2 | 197,466 | 0.658 | [1, 3, 1, 0] | Baseline full forest (5.9 MB joblib) |
| 100 | 5 | 72,790 | 0.658 | [1, 2, 1, 0] | Intermediate |
| 50 | 5 | 36,436 | 0.663 | [1, 2, 1, 0] | Selected · 1.28 MB JSON (0.690 aligned / 0.688 raw) |
| 50 | 20 | 19,760 | 0.658 | [1, 1, 0.5, 0] | Over-regularized |
| 30 | 20 | 11,782 | 0.660 | [1, 1, 1, 0] | First rule pick (test F1 0.671) |
| 30 | 50 | 7,378 | 0.651 | [1, 1, 1, 0] | Too shallow |
- S beats are weak (F1 0.177): supraventricular ectopic beats closely resemble normal morphology and differ mainly in timing; the model often confuses S with N.
- Fusion (F) beats are not predicted: only 414 training beats existed across few patients; tuning F decision weight yielded 0.82 recall at 0.055 precision (thousands of false alarms), so F weight was set to 0 after inspecting test results.
- Test-set selection feedback: the first selection rule picked 30 trees (test macro F1 0.671, weaker V precision), which motivated updating the rule to best CV score under a 1 MB binary budget (selecting the 50-tree forest).
- Local R-R context omitted: adding the previous-10-beat R-R context (63 features) lowered CV macro F1 (0.510 vs 0.522) and was not kept.
- Single-lead, single-database scope: evaluated only on MIT-BIH lead MLII; not validated on other ECG leads, wearables, or clinical populations.
- Educational project only: not a medical device and not intended for diagnosis.
MIT-BIH DS2 Sample Library
All six built-in recordings belong to DS2 (unseen test patients 100, 200, and 233). Load any record directly into the studio workspace or download the raw single-lead CSV.
End-to-End Architecture & Scientific Grounding
- Input & Resampling: Single-lead mV samples (MIT-BIH JSON, 60 s CSV, or user CSV/TXT at 100–2000 Hz) are linearly resampled to 360 Hz (
resample_linear). - Zero-Phase Band-Pass Filtering: 3rd-order Butterworth 0.5–40 Hz (3 biquad SOS sections) applied forward and backward with odd extension (
padlen = 720). - Pan–Tompkins R-Peak Detection: 2nd-order 5–15 Hz band-pass, 5-point derivative scaled by
fs/8, squaring, 150 ms centered moving-window integration, adaptive thresholds with 200 ms refractory period and1.66×RRsearch-back, plus ±80 ms peak-deflection refinement. - Beat Segmentation: Each interior peak
pextracts[p − 90, p + 110)(200 samples, ~556 ms). Boundary beats lacking a full window or neighbor R-R interval are skipped. - 57-Feature Extraction: 5 R-R timing features, 12 baseline-subtracted morphology descriptors, and a 40-point peak-to-peak normalized beat shape vector.
- Float32-Exact Random Forest Inference: Features are cast via
Math.fround(matching scikit-learnfloat32node splits) across all 50 trees inecg-forest.json. - Decision Weighting: Mean leaf probabilities are multiplied by
[1, 2, 1, 0]and argmax selects N, S, or V (F has weight 0).
AAMI EC57 Class Grouping
| AAMI Class | MIT-BIH Symbols Included | Training Beats (DS1) | Test Beats (DS2 aligned) | Handling |
|---|---|---|---|---|
| N Normal | N, L, R, e, j | 45,824 | 44,218 | Predicted (weight 1.0) |
| S Supraventricular | A, a, J, S | 943 | 1,836 | Predicted (weight 2.0) |
| V Ventricular | V, E | 3,788 | 3,219 | Predicted (weight 1.0) |
| F Fusion | F | 414 | 388 | Not predicted (weight 0.0) |
Q Unknown / Paced | /, f, Q | 8 | 7 | Dropped before training; paced records 102, 104, 107, 217 excluded |
DS1 — Training Patients (22 records)
101, 106, 108, 109, 112, 114, 115, 116, 118, 119, 122, 124, 201, 203, 205, 207, 208, 209, 215, 220, 223, 230
DS2 — Unseen Test Patients (22 records)
100, 103, 105, 111, 113, 117, 121, 123, 200, 202, 210, 212, 213, 214, 219, 221, 222, 228, 231, 232, 233, 234
← Biomedical AI LabECG case study ↗EEG Analysis Studio →Heart Risk Studio →