ECG Analysis Studio

Educational project · Not a medical device · All processing runs offline

Offline 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.

Loading model (1.3 MB) and samples…

Interactive ECG Analysis Workspace

src/portable.py parity · 100% browser-side

Loading annotated records…

Beats Analyzed
—
—
Heart Rate
—
—
Normal (N)
—
—
Supraventricular (S)
—
—
Ventricular (V)
—
—
Hover trace for timestamp & amplitude · scroll to zoom · drag to pan · click peak to inspect
15.0 s 0.0 s
N · Normal S · Supraventricular V · Ventricular Edge peak (no 200-sample window) Bottom ticks: expert .atr truth

Beat Morphology Inspector (200 samples)

Loading beat…

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…
signal processing · sos biquads · pan–tompkins

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.

sos_main (Butterworth order 3, 0.5–40 Hz zero-phase |H|²) sos_det (Butterworth order 2, 5–15 Hz detector |H|²) Dashed: −3 dB cutoff (0.707 amplitude / 0.50 power)

ResamplingLinear → 360 Hz
Zero-Phase Paddingpadlen = 720 (2.0 s)
MWI Window55 samples (~150 ms)
Refractory Period72 samples (200 ms)
Refinement Radius±28 samples (±78 ms)
Search-Back Rule> 1.66 × RR₈ · 0.5 × thr

Exact Second-Order Sections (ecg-config.json)

feature engineering · 57 features per beat

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)

IndicesGroupFeature(s)Exact Formula (src/portable.py)Units
0R-R Timingprev_rrpeaks[k] - peaks[k - 1]samples
1R-R Timingnext_rrpeaks[k + 1] - peaks[k]samples
2R-R Timingprev/nextprev_rr / next_rrratio
3R-R Timingprev/med_rrprev_rr / median(prev_rr)ratio
4R-R Timingnext/med_rrnext_rr / median(prev_rr)ratio
5Morphologyamp_rx[90] (after x = beat - median(beat))mV
6–8Morphologypeak, trough, p2pmax(x), min(x), peak - troughmV
9–10Morphologyt_peak, t_troughargmax(x) - 90, argmin(x) - 90samples
11Morphologywidthcount(|x[50:130]| > 0.3 * max(|x|))samples
12–14Morphologyenergy, area, sdsum(x²), sum(|x|), sqrt(mean((x - mean)²))mV² / mV
15–16Morphologyskew, kurtosism3 / m2^1.5, m4 / m2^2 - 3 (biased)dimless
17–56Beat Shapeshape_0 .. shape_39x[::5] / (p2p + 1e-8) (every 5th sample)normalized
model evaluation · 22 unseen test patients (ds2)

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)
ClassPrecisionRecallF1Test BeatsShare
N Normal0.9580.9720.96544,16789.1%
S Supraventricular0.2010.1580.1771,8253.7%
V Ventricular0.9010.9450.9233,1836.4%
F Fusion (weight 0)———3830.8%
N · Normal44,167 beats
0.965
S · Supraventricular1,825 beats
0.177
V · Ventricular3,183 beats
0.923
F · Fusion383 beats
— not predicted —
—

Model Shrinkage & Size Budget Study (09_shrink_model.ipynb)

TreesMin LeafTotal NodesCV Macro F1 (N,S,V)Decision WeightsStatus
2002197,4660.658[1, 3, 1, 0]Baseline full forest (5.9 MB joblib)
100572,7900.658[1, 2, 1, 0]Intermediate
50536,4360.663[1, 2, 1, 0]Selected · 1.28 MB JSON (0.690 aligned / 0.688 raw)
502019,7600.658[1, 1, 0.5, 0]Over-regularized
302011,7820.660[1, 1, 1, 0]First rule pick (test F1 0.671)
30507,3780.651[1, 1, 1, 0]Too shallow
Honest Limitations (from README.md):
  • 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.
sample library · unseen test patients (ds2)

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.

architecture · aami ec57 · attribution

End-to-End Architecture & Scientific Grounding

  1. 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).
  2. 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).
  3. 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 and 1.66×RR search-back, plus ±80 ms peak-deflection refinement.
  4. Beat Segmentation: Each interior peak p extracts [p − 90, p + 110) (200 samples, ~556 ms). Boundary beats lacking a full window or neighbor R-R interval are skipped.
  5. 57-Feature Extraction: 5 R-R timing features, 12 baseline-subtracted morphology descriptors, and a 40-point peak-to-peak normalized beat shape vector.
  6. Float32-Exact Random Forest Inference: Features are cast via Math.fround (matching scikit-learn float32 node splits) across all 50 trees in ecg-forest.json.
  7. 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 ClassMIT-BIH Symbols IncludedTraining Beats (DS1)Test Beats (DS2 aligned)Handling
N NormalN, L, R, e, j45,82444,218Predicted (weight 1.0)
S SupraventricularA, a, J, S9431,836Predicted (weight 2.0)
V VentricularV, E3,7883,219Predicted (weight 1.0)
F FusionF414388Not predicted (weight 0.0)
Q Unknown / Paced/, f, Q87Dropped 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

Attribution & Sources: MIT-BIH Arrhythmia Database (Moody GB, Mark RG. IEEE Eng Med Biol 20(3):45–50, 2001 · PhysioNet doi:10.13026/C2F305), available under the Open Data Commons Attribution License v1.0 (ODC-By). Inter-patient split: de Chazal P, O'Dwyer M, Reilly RB, IEEE Trans Biomed Eng 51(7):1196–1206, 2004. PhysioToolkit: Goldberger AL et al., Circulation 101(23):e215–e220, 2000. Repository: ecg-arrhythmia-classification ↗ · Case study: ECG case study ↗ · Android APK v2.0.0: Download offline app ↗.

← Biomedical AI LabECG case study ↗EEG Analysis Studio →Heart Risk Studio →