Research

Methodology

The complete protocol behind every result on this platform, written so the study can be reviewed, reproduced and criticised.

Objectives

The platform studies automatic classification of single heartbeats from the electrocardiogram under conditions that resemble deployment on new patients. Three questions guide it:

  1. Performance: how do a 1D convolutional neural network, a support vector machine with an RBF kernel and a Random Forest compare on ANSI/AAMI EC57 heartbeat classes when the test patients are never seen during training or model selection?
  2. Robustness: how quickly does each model degrade when realistic noise (muscle artifact, electrode motion, baseline wander) is added at controlled signal-to-noise ratios?
  3. Explainability: which parts of the beat and which features drive each model, and do the explanations agree across model families?

Dataset

The MIT-BIH Arrhythmia Database (PhysioNet, version 1.0.0) contains 48 approximately half-hour excerpts of two-channel ambulatory ECG from 47 subjects, digitised at 360 samples per second per channel with 11-bit resolution over a 10 mV range. Each record carries reference beat annotations. The upper signal is a modified limb lead II (MLII) in most records; the lower is usually a modified V1 (occasionally V2, V4 or V5). Records 201 and 202 come from the same subject.

The models use the MLII lead only. The lead is selected by its name in each header rather than by position, because record 114 stores MLII as its second signal. Records 102 and 104 have no MLII lead; together with 107 and 217 they contain paced beats and are excluded, following the AAMI recommendation for arrhythmia algorithm evaluation. Files are read in WFDB format (header, format 212 signal file and MIT annotation file) and every decoded signal is verified against the 16-bit checksum stored in its header.

Heartbeat classes

Beat annotations are mapped to the five ANSI/AAMI EC57 classes. The Q class holds only a handful of beats in the non-paced records, so it is excluded from training and evaluation; the number of excluded Q beats is reported with every run.

AAMI classMIT-BIH annotation symbolsUsed
N: normal and bundle branch blockN, L, R, e, jYes
S: supraventricular ectopicA, a, J, SYes
V: ventricular ectopicV, EYes
F: fusion of ventricular and normalFYes
Q: paced, paced fusion, unclassifiable/, f, QExcluded

Patient-level split

Evaluation is inter-patient: no subject contributes beats to more than one partition. The starting point is the DS1 / DS2 division of de Chazal, O’Dwyer and Reilly (2004), which is widely used for comparison:

  • DS1 (training): 101 106 108 109 112 114 115 116 118 119 122 124 201 203 205 207 208 209 215 220 223 230
  • DS2 (test): 100 103 105 111 113 117 121 123 200 202 210 212 213 214 219 221 222 228 231 232 233 234

Because records 201 (DS1) and 202 (DS2) come from the same subject, the original division leaks one patient across partitions. The default subject-disjoint scheme removes record 202 from the test set. The original division remains selectable for comparison with literature and is flagged by the leakage audit.

Model selection never touches DS2. Up to four DS1 patients are held out as a validation set by a deterministic, seeded procedure that uses training labels only: records are visited in a seeded random order and added until the validation set holds at least 15% of the S and V beats of DS1, skipping any record that alone contains more than 40% of a minority class (so the training set keeps the dominant F and S sources). The validation set drives CNN early stopping and SVM probability calibration. An automated audit verifies that training, validation and test partitions share no subject and stores the result in each run.

Preprocessing

  • Physical units: digital samples are converted with (d − baseline) / gain from the header; uncalibrated signals use the WFDB default gain of 200 adu/mV.
  • Band-limiting: a zero-phase 4th-order Butterworth band-pass from 0.5 to 40 Hz removes baseline wander and high-frequency noise. Each Butterworth filter is a cascade of second-order sections designed by the bilinear transform with frequency pre-warping, equivalent to scipy.signal.butter. Zero-phase filtering runs forward and backward with odd-extension padding (1 s) and steady-state initial conditions, the default scheme of scipy.signal.sosfiltfilt, which suppresses edge transients (the initial-state problem of forward-backward filtering is analysed by Gustafsson, 1996). An optional second-order notch (50 or 60 Hz, Q = 30) can be added.
  • Fiducial alignment: each reference annotation is moved to the largest absolute deflection of the filtered signal within ±50 ms. Detected beats in new recordings are refined with the same rule, so training and inference share one fiducial definition.
  • Beat detection on new recordings: a zero-phase variant of the Pan-Tompkins algorithm (1985): 5 to 15 Hz band-pass, five-point derivative, squaring, 150 ms moving-window integration, adaptive dual thresholds, a 200 ms refractory period, slope-based T-wave rejection within 360 ms and search-back after 1.66 times the average RR interval. Recordings at other sampling rates are resampled to 360 Hz (anti-aliasing low-pass at 45% of the target rate, then linear interpolation).

Beat representation

Each beat is a 711 ms window from 250 ms before to 461 ms after the R peak (256 samples at 360 Hz), decimated to 180 Hz by averaging sample pairs after the 40 Hz low-pass, giving 128 samples with the R peak at index 45. The median of the window is subtracted. The first and last beat of each record only provide RR context.

The RR context of a beat consists of the pre-RR and post-RR intervals, the mean of the ten surrounding RR intervals and the mean RR within ±150 s. The CNN receives four dimensionless ratios (pre-RR and post-RR over the local mean, pre-RR over post-RR, local over long-term mean); these patient-normalised quantities are known to generalise better across patients than absolute intervals.

Hand-crafted features

The SVM and Random Forest read 38 features computed from the same 128-sample beat and its RR context, in 6 groups:

GroupFeatures
RhythmPre-RR interval; Post-RR interval; Local mean RR (10 beats); Mean RR (5 min window); Pre-RR / local RR; Post-RR / local RR; Pre-RR / post-RR; Pre-RR / mean RR
QRS complexR-peak amplitude; Q-wave amplitude; S-wave amplitude; QRS peak-to-peak; QRS width; QRS mean power; QRS positive area; QRS negative area; Max upstroke slope; Max downstroke slope; Beat skewness; Beat excess kurtosis
RepolarisationT-wave amplitude; R-to-T peak latency
Atrial activityP-wave amplitude
Waveform samplesAmplitude at R −100 ms; Amplitude at R −75 ms; Amplitude at R −50 ms; Amplitude at R −25 ms; Amplitude at R +25 ms; Amplitude at R +50 ms; Amplitude at R +75 ms; Amplitude at R +100 ms; Amplitude at R +150 ms; Amplitude at R +200 ms; Amplitude at R +250 ms; Amplitude at R +300 ms
Patient-relativeCorrelation with patient template; Distance from patient template; R amplitude / patient median

The patient template is the element-wise median beat of the record (or uploaded recording). It is computed without labels, which is possible in deployment because it only uses the patient’s own recording; it makes the method transductive at the recording level, which is stated as a limitation below.

Models and training

Training data

All S, V and F beats of the training patients are used. Normal beats are capped at 1,200 per training record by seeded random selection (configurable), which reduces the dominance of the N class and the training time without discarding minority-class information.

1D convolutional neural network

Three convolution blocks (16 filters of width 7, 32 of width 5, each followed by batch normalisation, ReLU and max-pooling by two; then 64 filters of width 5 with ReLU) are summarised by global average pooling and concatenated with a 16-unit ReLU branch on the four RR ratios, followed by a 64-unit ReLU layer, dropout of 0.3 and a softmax over N, S, V and F. The network has about 19,000 parameters, with seeded weight initialisation. Training uses Adam (learning rate 0.001, halved every five epochs), mini-batches of 128 drawn with class-balanced sampling (sampling mass proportional to class size raised to 0.3, i.e. balance exponent 0.7), waveform augmentation (amplitude ×0.85 to 1.15, Gaussian offset with SD 0.05 mV, shifts of ±2 samples, Gaussian noise up to 0.04 mV), up to 14 epochs, early stopping on validation macro-F1 with patience 4, and restoration of the best weights.

Support vector machine

Features are standardised on the training set. The RBF kernel k(x, x′) = exp(−γ‖x − x′‖²) is approximated with 512 random Fourier features (Rahimi and Recht, 2007), with γ = 1 / number of features as in the scikit-learn scale heuristic for standardised data. A linear one-vs-rest SVM with L2-regularised hinge loss (λ = 10⁻⁴) and class-balanced sample weights is trained by stochastic sub-gradient descent with learning rate 1 / (λ(t + t₀)), 12 epochs, in the style of Pegasos. Decision values are turned into probabilities by temperature scaling chosen on the validation set. This is an approximation of a kernel SVM, not an exact solution of the dual problem.

Random Forest

80 CART trees grown on bootstrap samples with Gini impurity, √38 ≈ 6 candidate features per split, maximum depth 14, at least 4 samples per leaf and class-balanced weights. Splits are searched over per-feature quantile histograms of up to 64 bins, the approach used by histogram-based gradient boosting, which keeps training fast. Class probabilities are averaged over trees.

Evaluation

  • Test set: every labelled N, S, V and F beat of the test patients (DS2), with no subsampling.
  • Per class (EC57 style): sensitivity, positive predictive value, false positive rate, specificity and F1, plus one-vs-rest ROC AUC and average precision from the predicted probabilities.
  • Overall: accuracy, macro-F1, balanced accuracy, Cohen’s kappa and the multi-class Matthews correlation coefficient (Gorodkin, 2004). Macro-F1 is the headline metric because accuracy is dominated by normal beats.
  • Uncertainty: 95% percentile confidence intervals from a patient-level bootstrap (500 resamples of test records with replacement, summing their confusion matrices), which respects the correlation between beats of one patient.
  • Model comparison: pairwise McNemar tests on per-beat correctness (exact binomial when fewer than 50 discordant beats, otherwise chi-square with continuity correction). Beats of one patient are not independent, so these p-values are optimistic; the patient-level intervals are the conservative comparison.
  • QRS detection: Pan-Tompkins sensitivity and positive predictive value on the test records, with a 150 ms matching window.

Noise robustness

Noise comes from the MIT-BIH Noise Stress Test Database (records bw, em, ma, first channel), recorded from active volunteers with electrodes placed where the ECG is not visible, plus optional synthetic white Gaussian noise and 60 Hz power-line interference. For every test record, a noise segment (seeded random offset) is added to the raw MLII signal of the first minutes of the record at a target SNR, defined as SNR = 10·log₁₀(var(signal) / var(scaled noise)). This variance-based definition differs from the QRS-amplitude-based definition of the original noise stress test, so absolute SNR values are not interchangeable with that work.

The full preprocessing, segmentation and feature extraction are re-run on the noisy signal and each model classifies the same beats at the reference beat locations (paired design: all S, V and F beats of the segment, normal beats capped at 250 per record), which isolates classifier robustness from detection errors. The QRS detector is evaluated separately on the same noisy signals.

Explainability

  • Grad-CAM (Selvaraju et al., 2017) on the last convolution layer of the CNN: channel weights are the time-averaged gradients of the class score; the ReLU of the weighted activation map is upsampled to the beat and scaled to [0, 1].
  • Integrated Gradients (Sundararajan et al., 2017) from a flat 0 mV baseline with a right Riemann sum, holding the RR inputs fixed. The completeness property (attributions sum to the change in output) is checked in the validation suite.
  • Occlusion sensitivity (Zeiler and Fergus, 2014) for all three models: each 44 ms window (8 samples, stride 2) is replaced by a straight line between its end points, features are recomputed, and the drop in class probability is attributed to the window. Using one model-agnostic method for all three models makes their explanations directly comparable.
  • Feature ablation for single beats: each feature is set to its training mean and the change in class probability recorded.
  • Permutation importance (Breiman, 2001) on a stratified subset of test beats: drop in macro-F1 when a feature column is shuffled, two repeats. For the Random Forest, impurity-based importance is also shown, with its known bias towards features with many split points.

Explanations describe models, not physiology

Attribution maps show what a trained model is sensitive to. They can be unstable, can disagree between methods, and should not be read as clinical evidence about a patient.

Implementation

The platform runs as one web application. Signal processing, feature extraction, the Random Forest, the SVM, all metrics and statistical tests are implemented in TypeScript; the CNN is implemented with TensorFlow.js (Smilkov et al., 2019) and trains on the GPU through WebGL, falling back to the CPU when WebGL is unavailable. Experiments execute in the researcher’s browser, which keeps data local and uses the local GPU. The algorithms follow the definitions of the standard scientific Python stack (SciPy filter design and zero-phase filtering, scikit-learn style Random Forest and SVM, PyTorch style CNN training), and their numerical behaviour is checked by the automated validation suite: analytic filter responses, WFDB checksums, beat counts against the PhysioNet record directory, QRS detection against reference annotations, model sanity checks and metric formulas.

Reproducibility

  • Every random choice (validation records, normal-beat subsampling, bootstrap, CNN initialisation, batch sampling and augmentation, Random Forest bootstraps, random Fourier features, robustness noise offsets) derives from the run seed through a deterministic generator.
  • GPU floating-point reductions are not bit-exact across devices, so CNN results can differ slightly between machines; Random Forest and SVM results are reproducible for a given seed and configuration.
  • Each run stores its full configuration, the compute backend, the GPU name and the application version, and can be exported as a JSON file containing results and trained models.

Limitations

  • One database: 47 subjects recorded between 1975 and 1979, mostly with a single analysed lead. Performance on other populations, devices and leads is unknown without external validation.
  • Inter-patient classification of S beats is difficult; results for S and F rest on few test patients, which the wide bootstrap intervals make visible.
  • RR features and the patient template use information from the surrounding recording (unlabelled); classification is not purely beat-local.
  • Beats are classified at reference locations in the main evaluation; end-to-end performance including detection errors is lower than the per-beat figures.
  • The SVM uses a random-feature approximation of the RBF kernel and the Random Forest uses histogram splits; both are standard approximations but are not identical to exact solvers.
  • This is an academic research platform. It is not a medical device, has not been clinically validated and must not be used for diagnosis or treatment.

Academic research platform. Not a clinically validated diagnostic device; never use its output for diagnosis or treatment.

Data: MIT-BIH Arrhythmia and Noise Stress Test databases (PhysioNet, ODC-By 1.0).

Made with Modulify