Preprint
Article

This version is not peer-reviewed.

The Accuracy Paradox in Medical AI: Evidence from Subject-Independent ECG Arrhythmia Classification

Submitted:

23 November 2026

Posted:

24 November 2026

You are already at the latest version

Abstract
Electrocardiogram (ECG) heartbeat classification is an important task for detecting cardiac arrhythmias. However, reliable classification remains challenging because of severe class imbalance and variations in ECG patterns across individuals. This study investigates the performance of two traditional machine learning models, Random Forest (RF) and XGBoost, for subject-independent ECG heartbeat classification using the MIT-BIH Arrhythmia Database. A total of 100,693 heartbeat segments from 43 subjects were classified into four categories: non-ectopic (N), supraventricular ectopic (S), ventricular ectopic (V), and fusion (F) beats. The dataset exhibited substantial class imbalance, with the fusion class accounting for only 0.80\% of all beats. A feature-based approach was developed using waveform-derived statistical and wavelet features, together with RR-interval features. Both classifiers were evaluated using a 43-fold Leave-One-Subject-Out (LOSO) protocol across three random seeds to assess their generalization to unseen subjects. Performance was measured using accuracy, balanced accuracy, macro-averaged F1-score, and class-wise evaluation metrics. XGBoost achieved a mean macro-F1 score of 0.4950 ± 0.0126 and balanced accuracy of 0.5243 ± 0.0152, outperforming Random Forest, which achieved 0.4413 ± 0.0108 and 0.4623 ± 0.0050, respectively. In contrast, Random Forest achieved higher overall accuracy (0.9212 ± 0.0072) than XGBoost (0.8615 ± 0.0045). Both models showed substantial difficulty identifying fusion beats, with near-zero F1-scores across all evaluated seeds. These findings illustrate the accuracy paradox in a medical AI setting: overall accuracy alone may not adequately represent model performance in highly imbalanced, subject-independent ECG classification. The results also highlight the persistent challenges of minority-class recognition and generalization across individuals.
Keywords: 
;  ;  ;  ;  ;  ;  ;  ;  

1. Introduction

Electrocardiography (ECG) is one of the most widely used non-invasive methods for monitoring cardiac electrical activity and identifying abnormalities in heart rhythm. The increasing availability of digital ECG recordings has created opportunities for automated heartbeat classification using machine learning techniques. Automated classification can assist in identifying different types of cardiac arrhythmias and may support clinical decision-making by reducing the need for manual examination of large volumes of ECG data. The MIT-BIH Arrhythmia Database has played an important role in the development and evaluation of automated ECG analysis methods by providing annotated ECG recordings for research purposes [1].
Traditional machine learning approaches commonly rely on handcrafted features extracted from ECG signals, including waveform morphology, statistical characteristics, and heartbeat interval information. These features can represent important differences between normal and abnormal heartbeats and can be combined with classifiers such as support vector machines, decision trees, and ensemble learning methods. Earlier work by de Chazal et al. demonstrated the use of ECG morphology and heartbeat interval features for automated heartbeat classification [2]. More recently, deep learning methods, particularly convolutional neural networks, have been investigated for learning discriminative representations directly from ECG waveforms. Despite these developments, the effectiveness of classification methods remains dependent on the characteristics and distribution of the training data.
One important challenge in ECG classification is the highly imbalanced distribution of heartbeat categories. In commonly used arrhythmia datasets, normal beats substantially outnumber several clinically relevant abnormal categories. Consequently, a classifier may achieve relatively high overall accuracy while performing poorly on less frequently represented classes. This phenomenon, known as the accuracy paradox [3], is of particular concern in medical AI, where the rare classes often correspond to the clinically important conditions that a model is expected to detect. This issue is particularly important in multi-class classification, where the recognition of minority arrhythmia categories is equally relevant to understanding overall model behaviour. Therefore, evaluation based only on accuracy may provide an incomplete view of model performance. Metrics such as macro-averaged F1-score, balanced accuracy, and class-specific precision and recall are necessary to examine how effectively a model handles both majority and minority classes [4].
Class imbalance and the identification of rare events are also important challenges in machine learning applications beyond healthcare. In financial markets, extreme price movements are difficult to detect because of their low frequency, non-stationary behaviour, and severely imbalanced data distributions. Recent work on high-frequency cryptocurrency markets has demonstrated the importance of considering class imbalance and target formulation when developing models for extreme event detection [5]. Similar difficulties arise in environmental and climate-related applications, where rare but critical events, such as extreme temperatures and tornadoes, require reliable predictive models. Previous work has investigated the use of machine learning and deep learning methods for forecasting such extreme climate events [6]. These examples illustrate the broader importance of evaluating machine learning models not only through overall accuracy but also through their ability to identify less frequently occurring but important events.
A second challenge concerns differences between individual patients. ECG signals may vary across subjects due to physiological differences, cardiac conditions, recording characteristics, and other sources of variability. When heartbeat segments are randomly divided into training and testing sets, beats from the same subject may appear in both partitions. This can allow a model to learn subject-specific characteristics and may result in an overly optimistic estimate of its ability to generalize to unseen individuals. Subject-independent evaluation is therefore important for assessing the generalization capability of ECG classification systems. In this study, a Leave-One-Subject-Out (LOSO) evaluation protocol is employed, ensuring that the subject used for testing is excluded from model training. Recordings belonging to the same individual are grouped together to prevent subject-level data leakage.
Motivated by these challenges, this study presents a comparative evaluation of traditional machine learning models for multi-class ECG heartbeat classification under severe class imbalance and subject-independent evaluation. The investigation uses the MIT-BIH Arrhythmia Database and considers four heartbeat categories: non-ectopic (N), supraventricular ectopic (S), ventricular ectopic (V), and fusion (F) beats. A feature-based representation is constructed by combining waveform-derived statistical descriptors, wavelet-based features, and RR-interval information. Random Forest and XGBoost are selected as the classification models to examine their performance under the same experimental evaluation protocol. Their generalization capability is assessed using 43 subject-level LOSO folds and three random seeds, with particular attention to minority-class recognition and consistency across experimental runs.
The main contributions of this study are summarized as follows:
  • Feature representation: Construct a heartbeat-level feature representation combining waveform-derived statistical descriptors, wavelet-based features, and RR-interval information.
  • Subject-independent evaluation: Establish a 43-fold Leave-One-Subject-Out evaluation protocol to assess generalization to unseen subjects while preventing subject-level data leakage.
  • Comparative model evaluation: Compare Random Forest and XGBoost using three random seeds and evaluate their performance through accuracy, macro-averaged F1-score, balanced accuracy, and class-specific precision, recall, and F1-score.
Through this investigation, the study aims to provide a systematic comparison of traditional machine learning approaches for ECG heartbeat classification under severe class imbalance and subject variability. By considering both overall predictive performance and minority-class recognition, the findings highlight the importance of evaluation strategies that better reflect generalization to previously unseen individuals.

3. Materials and Methods

3.1. Dataset Description

The MIT-BIH Arrhythmia Database [1,31], distributed through PhysioNet [32], was used to evaluate the performance of machine learning models for ECG heartbeat classification. The database contains annotated ambulatory electrocardiogram recordings sampled at 360 Hz. In this study, the modified limb lead II (MLII) channel was selected for heartbeat analysis.
A total of 44 recordings from 43 subjects were included in the final cohort. Records 102 and 104 were excluded because they did not contain the required MLII channel, while records 107 and 217 were excluded according to the predefined study protocol. These four records are the paced recordings of the database [31], and their exclusion is consistent with the AAMI-based practice commonly adopted in inter-patient studies [2]. Records 201 and 202 were grouped under a single subject identifier because they belong to the same individual. This grouping was maintained throughout the subject-independent evaluation to prevent data leakage between training and testing partitions.
The original heartbeat annotations were mapped into four AAMI-derived classes: normal (N), supraventricular ectopic (S), ventricular ectopic (V), and fusion (F). The annotation mapping is presented in Table 1.
After preprocessing and the exclusion of boundary-affected beats, the final dataset contained 100,693 heartbeat samples. The class distribution consisted of 90,102 normal beats (89.48%), 2,781 supraventricular ectopic beats (2.76%), 7,008 ventricular ectopic beats (6.96%), and 802 fusion beats (0.80%). This distribution demonstrates substantial class imbalance, particularly for the fusion class.
As illustrated in Figure 1, the dataset exhibits substantial class imbalance, with normal beats accounting for 89.48% of all observations.

3.2. ECG Preprocessing

The preprocessing pipeline was designed to reduce signal noise and extract fixed-length heartbeat segments from the original ECG recordings. First, a fourth-order Butterworth bandpass filter with cutoff frequencies of 0.5 Hz and 40 Hz was applied to each MLII signal. Zero-phase filtering was performed using the second-order-section implementation of sosfiltfilt to reduce phase distortion.
Following filtering, each recording was normalized using its median and interquartile range (IQR). The normalized signal was calculated as
x norm ( t ) = x filtered ( t ) − median ( x filtered ) IQR ( x filtered ) .
Heartbeat segmentation was performed using the R-peak locations provided by the original expert annotations. For each annotated heartbeat, a segment containing 180 samples was extracted, consisting of 90 samples before and 90 samples after the R-peak. At a sampling frequency of 360 Hz, this corresponds to a 0.5-second window centered on the annotated R-peak.
Segments for which the complete window was unavailable because of recording boundaries were excluded. This procedure resulted in the removal of 25 boundary-affected beats. The final dataset therefore contained 100,693 valid heartbeat segments.
Representative heartbeat segments from the four classes are shown in Figure 2.

3.3. Feature Extraction

Each heartbeat was represented by a 38-dimensional feature vector consisting of 33 waveform-derived features and five RR-interval features. The feature set was designed to capture complementary morphological, statistical, frequency-related, and temporal characteristics of ECG signals.

3.3.1. Waveform-Derived Features

The waveform-derived feature set consisted of three groups of time-domain features and one group of wavelet-based features.
First, six amplitude and statistical features were calculated from each 180-sample heartbeat segment: maximum amplitude, minimum amplitude, amplitude range, mean, standard deviation, and root mean square (RMS).
Second, four features were calculated from a fixed central region around the annotated R-peak to represent local QRS-related characteristics: maximum amplitude, minimum amplitude, amplitude range, and signal energy. This region was defined using 14 samples before and 15 samples after the R-peak. These measurements represent fixed-window QRS proxies rather than features obtained through a dedicated QRS delineation algorithm.
Third, three derivative-based features were extracted from the first-order differences of the heartbeat waveform: mean absolute derivative, derivative standard deviation, and maximum absolute derivative.
Finally, discrete wavelet decomposition was applied using the Daubechies-4 (db4) wavelet at decomposition level four. Five coefficient groups were obtained: the level-four approximation coefficients (cA4) and detail coefficients (cD4, cD3, cD2, and cD1). Four statistical descriptors were calculated for each coefficient group: standard deviation, mean, entropy, and maximum absolute coefficient. This resulted in 20 wavelet-based features.
The four-level db4 wavelet decomposition is illustrated in Figure 3.
Consequently, the waveform representation contained 33 features: six amplitude and statistical features, four QRS-related proxy features, three derivative-based features, and 20 wavelet-based features.

3.3.2. RR-Interval Features

Five RR-related features were extracted to represent the temporal relationships between consecutive annotated beats:
  • rr_previous: interval between the current and previous annotated beat.
  • rr_next: interval between the current and subsequent annotated beat.
  • rr_median_previous_10: median of the ten RR intervals ending at the current beat.
  • rr_previous_ratio: ratio of the previous RR interval to the median of the preceding ten RR intervals.
  • rr_next_ratio: ratio of the next RR interval to the same median reference.
The RR intervals were calculated using the sample positions of AAMI-classified heartbeat annotations and additional Q annotations. The latter were retained as temporal anchors for estimating the rhythm intervals, although they were not included as target heartbeat classes.
Missing RR values occurred at recording boundaries and were retained for subsequent imputation. Median imputation was fitted using only the training partition within each model-fitting procedure.
The combination of 33 waveform-derived features and five RR-related features resulted in a 38-dimensional feature representation for every heartbeat.
It is important to note that rr_next and rr_next_ratio use information from the subsequent heartbeat. Therefore, the feature representation corresponds to an offline, retrospective classification setting rather than a strictly causal real-time classification system. Furthermore, the RR features were calculated from expert annotations rather than from an independently operating heartbeat detection algorithm.

3.4. Class Distribution and Subject-Level Characteristics

In addition to examining the overall class distribution, the occurrence of each heartbeat class across individual subjects was investigated. This analysis was performed to characterize the distribution of minority-class examples within the cohort.
The distribution of heartbeat classes across individual subjects is presented in Figure 4.
Ventricular ectopic beats were present in 32 subjects, supraventricular ectopic beats in 31 subjects, and fusion beats in 16 subjects. The fusion class was particularly concentrated in a small number of individuals, with subjects 208 and 213 contributing approximately 91.5% of all fusion beats.
This subject-level variation is relevant to subject-independent evaluation because a held-out subject may contain heartbeat classes that are poorly represented or absent in the training subjects. The distribution of minority classes across subjects was therefore considered when interpreting the classification results.

3.5. Classification Models

Two tree-based ensemble learning algorithms, Random Forest and Extreme Gradient Boosting (XGBoost), were selected for comparative evaluation. Both models were trained using the same 38-dimensional feature representation.

3.5.1. Random Forest

Random Forest is an ensemble learning method that combines predictions from multiple decision trees. Each tree is trained using a bootstrap sample of the training data, while random feature selection at each split introduces diversity among the individual trees.
In this study, the Random Forest classifier was configured with 300 estimators, square-root feature selection (max_features=sqrt), and a minimum of two samples per leaf. The balanced_subsample class-weighting strategy was applied to account for class imbalance within the bootstrap samples. The random state was controlled using the predefined experimental seeds.

3.5.2. Extreme Gradient Boosting

XGBoost is a gradient-boosted decision tree algorithm in which trees are constructed sequentially to improve the predictions of the existing ensemble. The model minimizes a regularized objective function and can capture nonlinear relationships among the extracted ECG features.
The XGBoost classifier was configured with 300 estimators, a maximum tree depth of four, and a learning rate of 0.05. The row subsampling and column subsampling ratios were both set to 0.8. The L2 regularization parameter was set to 2.0, and the minimum child weight was set to 2. The histogram-based tree construction method was used with multiclass probability output.
To address class imbalance, balanced sample weights were calculated from the class distribution of the training data and supplied during model fitting. Class labels were encoded into consecutive integer values for model training, and the resulting probability columns were restored to the original class order (N, S, V, F) during evaluation.
For both classifiers, missing feature values were handled using median imputation. The imputer was fitted on the relevant training partition and subsequently applied to the corresponding validation or test partition.

3.6. Experimental Protocol

A Leave-One-Subject-Out (LOSO) cross-validation strategy was adopted to assess the ability of the models to generalize to previously unseen subjects. Since the final cohort contained 43 subjects, the outer evaluation consisted of 43 folds.
In each fold, all heartbeat samples belonging to one subject were reserved for testing, while the remaining 42 subjects were used for model development. This procedure was repeated until every subject had been used once as the held-out test subject. Records 201 and 202 were treated as a single subject throughout this process.
Within each outer training partition, a subject-grouped inner validation split was generated using a 20% validation fraction. The inner split was selected from grouped candidate partitions to ensure that the validation data contained ventricular ectopic beats and at least one additional class whenever possible. This validation partition was used for probability calibration and V-class threshold selection.
After these procedures, the model was refitted using all available data from the outer training subjects. The held-out subject remained excluded from model fitting, calibration, and threshold selection.
To examine the effect of random initialization and data partitioning, the complete evaluation was repeated using three random seeds: 42, 123, and 2026. The final experimental design therefore consisted of 43 outer folds, two classification models, and three random seeds, resulting in 258 model-fold evaluations.

3.7. Probability Calibration and V-Class Threshold Selection

Probability calibration was performed using temperature scaling on the inner validation partition. Since both Random Forest and XGBoost provide class probabilities rather than raw logits, the predicted probabilities were first converted into log-probability scores. For each class c, the score was calculated as
z c = log max ( p c , 10 − 8 ) ,
where p c denotes the predicted probability for class c. The clipping operation prevents numerical issues when a predicted probability is close to zero.
Given the resulting score vector z and a positive temperature parameter T, calibrated class probabilities were obtained using
P ( y = c ∣ x ) = exp ( z c / T ) ∑ j = 1 C exp ( z j / T ) ,
where C = 4 represents the number of heartbeat classes. The temperature parameter was estimated by minimizing the multiclass negative log-likelihood on the inner validation data. A bounded scalar optimization procedure was used to search for a temperature value between 0.05 and 20.
After temperature scaling, a decision threshold was selected for the ventricular ectopic (V) class. Candidate thresholds were evaluated using the validation predictions, and the threshold maximizing the binary F1-score for the V class was selected. The candidate set included values between 0.05 and 0.95, together with the validation probabilities and a default threshold of 0.50.
For a given heartbeat, the V class was predicted when its calibrated probability was greater than or equal to the selected threshold. Otherwise, the class with the highest probability among N, S, and F was selected.
When the validation partition did not contain sufficient V-class support, the predefined fallback threshold of 0.50 was used. Both the temperature parameter and the V-class threshold were determined using only the inner validation data and were subsequently applied to the held-out subject.

3.8. Evaluation Metrics

The classification performance of Random Forest and XGBoost was evaluated using accuracy, balanced accuracy, macro-averaged F1-score, weighted F1-score, and class-wise F1-score.
Accuracy measures the proportion of correctly classified samples among all predictions:
Accuracy = 1 N ∑ i = 1 N ⊩ ( y i = y ^ i ) ,
where N denotes the total number of samples, y i is the true class, and y ^ i is the predicted class. The indicator function ⊩ ( · ) equals 1 when its condition is true and 0 otherwise.
Balanced accuracy is calculated as the average recall across all classes:
Balanced Accuracy = 1 C ∑ c = 1 C Recall c .
The macro-averaged F1-score gives equal importance to each class:
Macro - F 1 = 1 C ∑ c = 1 C F 1 c .
The weighted F1-score accounts for the number of samples belonging to each class:
Weighted - F 1 = ∑ c = 1 C N c N F 1 c ,
where N c represents the number of samples belonging to class c, and C = 4 represents the four heartbeat classes (N, S, V, and F).
Finally, class-wise F1-scores were calculated separately for N, S, V, and F to examine the recognition performance for individual heartbeat categories. All metrics were calculated from the held-out predictions. Results across the three random seeds were summarized using the mean and standard deviation to describe variation associated with the random seed.

4. Results

4.1. Pooled Performance

Table 2 reports the pooled performance computed over the held-out predictions from all 43 LOSO folds (100,693 heartbeat predictions per model and seed), and Figure 5 compares the two models across the three random seeds.
Across the three random seeds, RF achieved a mean accuracy of 0.9212 ± 0.0072 and a mean weighted-F1 score of 0.9112 ± 0.0062 . In comparison, XGBoost achieved a mean accuracy of 0.8615 ± 0.0045 and a weighted-F1 score of 0.8902 ± 0.0050 .
However, XGBoost demonstrated stronger performance when all four heartbeat classes were considered equally. Its mean balanced accuracy was 0.5243 ± 0.0152 , compared with 0.4623 ± 0.0050 for RF. Similarly, XGBoost achieved a mean macro-F1 score of 0.4950 ± 0.0126 , exceeding the RF score of 0.4413 ± 0.0108 .
These results indicate that overall accuracy alone does not adequately describe classification performance in this highly imbalanced dataset.

4.2. Class-Wise Classification Performance

To examine the classification behaviour of each model across the four heartbeat classes, class-wise precision, recall, and F1-score were analysed. Table 3 summarizes the mean F1-score across the three random seeds.
Both models achieved their strongest classification performance for the normal (N) heartbeat class. RF obtained a mean F1-score of 0.9577, while XGBoost achieved 0.9245.
For the supraventricular ectopic (S) class, XGBoost achieved a substantially higher mean F1-score of 0.2316, compared with 0.0466 for RF. A similar improvement was observed for the ventricular ectopic (V) class, where XGBoost achieved 0.8120 compared with 0.7609 for RF.
Nevertheless, both models showed considerable difficulty recognizing the fusion (F) class. RF obtained an F1-score of zero across all three seeds, while XGBoost achieved a very low mean F1-score of 0.0120.
The class-wise results demonstrate that XGBoost provides better recognition of the S and V classes, although performance on the rare F class remains limited.

4.3. Subject-Level Evaluation

In addition to pooled classification metrics, model performance was examined across the 43 held-out subjects. For each LOSO fold, the model was evaluated on a subject that was not included in the corresponding training data. The mean and standard deviation of balanced accuracy and macro-F1 across the subject-level folds are reported in Table 4.
For subject-level evaluation, balanced accuracy was calculated over the classes present in the corresponding held-out subject. Macro-F1 was calculated over all four predefined heartbeat classes (N, S, V, and F), with zero assigned to classes with undefined F1-scores.
XGBoost achieved higher mean subject-level balanced accuracy than RF across all three seeds. Its mean balanced accuracy remained approximately 0.733, while RF achieved values between 0.621 and 0.641.
The subject-level macro-F1 results also favoured XGBoost, although the difference was smaller than that observed for balanced accuracy. The standard deviations indicate considerable variation in classification performance between held-out subjects. This variation highlights the importance of evaluating ECG classification models across different individuals rather than relying exclusively on pooled heartbeat-level performance.
The distribution of subject-level performance is further illustrated in Figure 6, which shows the variation in model performance across the held-out individuals.

4.4. Confusion Matrix Analysis

The confusion matrices provide further insight into the classification errors made by the two models. In particular, they reveal differences in the recognition of minority heartbeat classes.
For RF, most normal beats were correctly classified as N. However, a substantial proportion of S beats were incorrectly classified as N. The model also failed to correctly identify the F class across all three random seeds.
XGBoost showed a different classification pattern. Although its recognition of normal beats was slightly lower than that of RF, it correctly identified a larger proportion of S beats. It also demonstrated improved recognition of V beats. Nevertheless, misclassification of F beats remained a major challenge.
These observations are consistent with the class-wise F1-score results and further demonstrate the limitations of both models under severe class imbalance. The normalized confusion matrices in Figure 7 provide a class-proportion-based view of these prediction patterns.

5. Discussion

5.1. Comparison of Random Forest and XGBoost

The experimental results reveal different strengths of Random Forest and XGBoost in subject-independent ECG heartbeat classification. RF achieved higher accuracy and weighted-F1 scores, whereas XGBoost consistently achieved higher balanced accuracy and macro-F1 scores.
This difference is mainly related to the severe class imbalance in the MIT-BIH Arrhythmia Database. Normal heartbeats account for approximately 89.48% of the observations. Consequently, performance on the majority class has a substantial influence on accuracy and weighted-F1 scores.
RF demonstrated strong recognition of normal heartbeats, which contributed to its higher overall accuracy. However, its limited recognition of the S class and failure to identify the F class reduced its macro-F1 performance.
In contrast, XGBoost achieved better F1-scores for both S and V classes. Its higher balanced accuracy and macro-F1 scores suggest that it provides a more balanced classification performance across the evaluated heartbeat categories. Therefore, the results do not indicate that one model is universally superior. Instead, model selection depends on the evaluation objective and the importance assigned to minority-class recognition.
This pattern is a concrete instance of the accuracy paradox [3] and has a broader implication for the evaluation of medical AI systems. In the present experiments, the model with the higher overall accuracy (RF) did not correctly identify any fusion beat in any of the three seeds and recognized only a small proportion of supraventricular ectopic beats. A ranking based on accuracy alone would therefore favour the model that is less effective at detecting the minority arrhythmia classes. Reporting class-balanced metrics, class-wise results, and subject-level variability alongside accuracy provides a more informative basis for assessing whether such a model is suitable for clinical decision support.

5.2. Effect of Severe Class Imbalance

The results demonstrate that class imbalance remains a major challenge for feature-based ECG classification. Although the dataset contains 100,693 heartbeat observations, only 802 belong to the F class, representing approximately 0.80% of the dataset.
The difficulty is not limited to the small number of F observations. The distribution of this class across subjects is also highly concentrated. In particular, two subjects contribute approximately 91.5% of all F-class observations. Furthermore, the F class is absent from 27 of the 43 held-out subject folds.
This distribution creates a difficult evaluation condition. During some LOSO iterations, the training data contain very limited examples of a minority class, while the held-out subject may contain examples that are poorly represented during training.
The zero F-class F1-score obtained by RF and the very low score obtained by XGBoost should therefore be interpreted in the context of both class imbalance and subject-level class concentration. These findings suggest that the number of observations alone does not fully describe the difficulty of minority-class recognition. Their distribution across individual subjects is also important.

5.3. Subject-independent Generalization

A central aspect of this study is the use of leave-one-subject-out evaluation. Unlike beat-level random splitting, this protocol ensures that the heartbeat observations from the test subject are excluded from the corresponding training data.
The subject-level results show that XGBoost achieved higher mean balanced accuracy across the evaluated subjects. However, the standard deviations of the fold-level metrics indicate noticeable variation between individuals.
This variation suggests that classification performance is influenced by differences in heartbeat morphology, rhythm patterns, and the availability of minority-class examples across subjects.
The findings also highlight why pooled performance and subject-level performance should be reported separately. Pooled metrics summarize performance across all heartbeat predictions, whereas fold-level metrics describe how performance varies between held-out individuals. Reporting both provides a more complete assessment of subject-independent classification.

5.4. Limitations

Several limitations should be considered when interpreting the results.
First, the evaluation was conducted using the MIT-BIH Arrhythmia Database. Although it is a widely used benchmark, the findings may not generalize directly to other ECG databases or clinical populations.
Second, the F class was highly concentrated in a small number of subjects. This limited distribution affected the availability of minority-class observations during LOSO training and evaluation.
Third, the feature extraction process included future-looking RR interval features, including the next RR interval and its normalized ratio. In addition, zero-phase filtering was performed using forward-backward filtering. Therefore, the current pipeline represents an offline, retrospective classification setting rather than a strictly causal real-time system.
Fourth, RR interval features were calculated using expert-provided beat annotations. The study therefore does not evaluate the additional errors that may arise from an automatic R-peak detection system.
Finally, the comparison was restricted to Random Forest and XGBoost using a fixed feature-based representation. Other feature engineering strategies and classification approaches were not investigated in this study.

6. Conclusions

This study compared Random Forest and XGBoost for four-class ECG heartbeat classification on the MIT-BIH Arrhythmia Database under a 43-fold leave-one-subject-out protocol repeated over three random seeds. The main findings can be summarized as follows:
  • XGBoost achieved higher macro-F1 and balanced accuracy than Random Forest across all three random seeds, indicating better recognition of minority heartbeat classes.
  • Random Forest achieved higher overall accuracy and weighted-F1, mainly due to its stronger performance on the majority N class.
  • Both models struggled to recognize the F class, highlighting the challenges associated with severe class imbalance and the concentration of minority-class samples across subjects.
More broadly, these results indicate that in medical AI applications with rare but clinically important classes, accuracy should be reported together with class-balanced and subject-level metrics. Natural extensions of this work include causal feature sets suitable for real-time use, automatically detected R-peaks, and evaluation on additional ECG databases.

References

  1. G. B. Moody and R. G. Mark, “The impact of the MIT-BIH Arrhythmia Database,” IEEE Engineering in Medicine and Biology Magazine, vol. 20, no. 3, pp. 45–50, 2001. [CrossRef]
  2. P. de Chazal, M. O’Dwyer, and R. B. Reilly, “Automatic classification of heartbeats using ECG morphology and heartbeat interval features,” IEEE Transactions on Biomedical Engineering, vol. 51, no. 7, pp. 1196–1206, 2004. [CrossRef]
  3. F. J. Valverde-Albacete and C. Peláez-Moreno, “100% classification accuracy considered harmful: The normalized information transfer factor explains the accuracy paradox,” PLoS ONE, vol. 9, no. 1, Art. no. e84217, 2014. [CrossRef]
  4. M. Sokolova and G. Lapalme, “A systematic analysis of performance measures for classification tasks,” Information Processing and Management, vol. 45, no. 4, pp. 427–437, 2009. [CrossRef]
  5. M. Zaman and H. M. Sahed, “Volatility-Aware Extreme Event Detection in High-Frequency Financial Markets,” arXiv preprint arXiv:2607.17555, 2026.
  6. H. M. Sahed, M. A. S. Showrob, and F. Ozaydin, “Evaluation of Machine Learning and Deep Learning Models for Extreme Climate Event Forecasting,” in 2025 International Conference on Advanced Machine Learning and Data Science (AMLDS), pp. 484–489, 2025. [CrossRef]
  7. N. Emanet, “ECG beat classification by using discrete wavelet transform and Random Forest algorithm,” in 2009 Fifth International Conference on Soft Computing, Computing with Words and Perceptions in System Analysis, Decision and Control (ICSCCW), 2009, pp. 1–4. [CrossRef]
  8. N. Sharma, R. K. Sunkaria, and A. Kaur, “Electrocardiogram heartbeat classification using machine learning and ensemble convolutional neural network–bidirectional long short-term memory technique,” IEEE Transactions on Artificial Intelligence, 2023. [CrossRef]
  9. E. V. Alforja and J. C. Aban, “Timing and context features in machine learning classification of inter-patient ECG heartbeats on the MIT-BIH benchmark,” medRxiv, 2026. [CrossRef]
  10. B. Fatimah, A. Singhal, and P. Singh, “ECG arrhythmia detection in an inter-patient setting using Fourier decomposition and machine learning,” Medical Engineering & Physics, 2024, Art. no. 104102. [CrossRef]
  11. A. S. Mirdan, “Overcoming class overlap and imbalance in ECG detection and classification: A deep attention-based model on MIT-BIH,” Journal of Al-Qadisiyah for Computer Science and Mathematics, vol. 17, no. 2, pp. 29–47, 2025. [CrossRef]
  12. H. Xiao, B. Zhang, Q. Xia, B. Jiang, Z. Ran, X. Zhu, and W.-S. Song, “A deep learning approach of heartbeat classification for the single-lead ECG signals and inter-patient paradigm,” in 2nd International Conference on Signal Image Processing and Communication (ICSIPC 2022), Proc. SPIE, vol. 12246, Art. no. 1224606, 2022. [CrossRef]
  13. Z. Wang, X. Chen, Y. Zheng, and X. Wu, “A deep learning approach for inter-patient classification of premature ventricular contraction from electrocardiogram,” Biomedical Signal Processing and Control, 2024. [CrossRef]
  14. T. Sarker and R. I. Munna, “Multi-class arrhythmia classification using a dual-model ensemble framework,” in 2026 IEEE 2nd International Conference on Quantum Photonics, Artificial Intelligence and Networking (QPAIN), Chittagong, Bangladesh, 2026, pp. 1–6. [CrossRef]
  15. M. Z. A. Hadba, A. J. Zaylaa, and M. Ayache, “A new multi-class framework for electrocardiogram arrhythmia classification using artificial intelligence,” in 2026 IEEE 5th International Multidisciplinary Conference on Engineering Technology (IMCET), Beirut, Lebanon, 2026, pp. 1–6. [CrossRef]
  16. M. Ahmadabadi and A. Sadr, “A two-stage hierarchical deep learning model for inter-patient arrhythmia classification,” in 2026 34th International Conference on Electrical Engineering (ICEE), Tehran, Iran, 2026, pp. 308–314. [CrossRef]
  17. F.-Y. Zhou, Y.-H. Sun, and Y.-W. Wang, “Inter-patient ECG arrhythmia heartbeat classification network based on multiscale convolution and FCBA,” Biomedical Signal Processing and Control, 2023. [CrossRef]
  18. M. Zubair, S. Woo, S. Lim, and D. Kim, “Deep representation learning with sample generation and augmented attention module for imbalanced ECG classification,” IEEE Journal of Biomedical and Health Informatics, vol. PP, 2023. [CrossRef]
  19. R. F. Oliveira, G. Moreira, V. L. S. Freitas, and E. Luz, “Leveraging visibility graphs for enhanced arrhythmia classification with graph convolutional networks,” arXiv:2404.15367, 2024.
  20. Abdullah, Z. Fatima, A. Abadian, C. G. S. Mejorada, M. J. T. Ruiz, and R. Q. Tellez, “Integration of machine learning techniques in ECG-based multiclass arrhythmia classification with explainability analysis,” Biosensors, 2026. [CrossRef]
  21. S. Singha, A. Saha, P. Dhar, A. Alam, S. Hossen, and A. Chowdhury, “MIT-BIH ECG arrhythmia multi-class classification using AdamW-optimized deep ensembles with SMOTE-based sampling,” in 2026 IEEE 2nd International Conference on Quantum Photonics, Artificial Intelligence and Networking (QPAIN), Chittagong, Bangladesh, 2026, pp. 1–6. [CrossRef]
  22. T. H. Rafi and Y. Ko, “SF-ECG: Source-free intersubject domain adaptation for electrocardiography-based arrhythmia classification,” Applied Sciences, 2023. [CrossRef]
  23. A. Tibermacine, I. E. Tibermacine, M. Mancer, I. Naidji, L. Mamen, A. Rabehi, and M. Habib, “Cross-lead attention transformers with GAN oversampling for robust ECG arrhythmia detection,” Electronics, vol. 15, no. 6, p. 1258, 2026. [CrossRef]
  24. Z. Ran, M. Jiang, Y. Li, Z. Wang, Y. Wu, W. Ke, and L. Xia, “Arrhythmia classification based on multi-feature multi-path parallel deep convolutional neural networks and improved focal loss,” Mathematical Biosciences and Engineering, vol. 21, no. 4, pp. 5521–5535, 2024. [CrossRef]
  25. H. Wu, S. Zhang, B. Bao, J. Li, Y. Zhang, D. Qiu, and H. Yang, “A deep neural network ensemble classifier with focal loss for automatic arrhythmia classification,” Journal of Healthcare Engineering, vol. 2022, pp. 1–11, 2022. [CrossRef]
  26. H. Elgazzar, “Automated ECG arrhythmia classification using convolutional neural networks with effective class imbalance handling,” Applied Sciences, vol. 16, no. 11, p. 5321, 2026. [CrossRef]
  27. M. Liu, N. Shao, C. Zheng, and J. Wang, “Real time arrhythmia monitoring and classification based on edge computing and DNN,” Wireless Communications and Mobile Computing, vol. 2021, pp. 1–9, 2021. [CrossRef]
  28. S. Mousavi and F. Afghah, “Inter- and intra-patient ECG heartbeat classification for arrhythmia detection: A sequence to sequence deep learning approach,” in Proc. IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP), Brighton, UK, 2019, pp. 1308–1312. [CrossRef]
  29. J. Zhang, A. Liu, D. Liang, X. Chen, and M. Gao, “Interpatient ECG heartbeat classification with an adversarial convolutional neural network,” Journal of Healthcare Engineering, vol. 2021, p. 9946596, 2021. [CrossRef]
  30. A. Sadr, “A hierarchical deep learning framework for inter-patient cardiac arrhythmia classification with class imbalance handling,” Scientific Reports, 2026 (article in press). [CrossRef]
  31. G. Moody and R. Mark, “MIT-BIH Arrhythmia Database (version 1.0.0),” PhysioNet, 2005, RRID:SCR_007345. [CrossRef]
  32. T. Pollard, B. E. Moody, L. Lehman, B. Gow, C. Fernandes, C. Xie, A. Johnson, R. G. Mark, and T. Heldt, “PhysioNet as a global platform for biomedical research,” Nature Health, vol. 1, no. 8, pp. 792–795, 2026. [CrossRef]
Figure 1. Distribution of the four AAMI-derived heartbeat classes in the MIT-BIH Arrhythmia Database. The dataset contains 90,102 normal (N), 2,781 supraventricular ectopic (S), 7,008 ventricular ectopic (V), and 802 fusion (F) beats.
Figure 1. Distribution of the four AAMI-derived heartbeat classes in the MIT-BIH Arrhythmia Database. The dataset contains 90,102 normal (N), 2,781 supraventricular ectopic (S), 7,008 ventricular ectopic (V), and 802 fusion (F) beats.
Preprints 245923 g001
Figure 2. Representative ECG heartbeat segments from the four AAMI-derived classes: normal (N), supraventricular ectopic (S), ventricular ectopic (V), and fusion (F). The dashed vertical line indicates the annotated R-peak, which serves as the temporal reference for heartbeat segmentation.
Figure 2. Representative ECG heartbeat segments from the four AAMI-derived classes: normal (N), supraventricular ectopic (S), ventricular ectopic (V), and fusion (F). The dashed vertical line indicates the annotated R-peak, which serves as the temporal reference for heartbeat segmentation.
Preprints 245923 g002
Figure 3. Four-level discrete wavelet decomposition of a representative ECG heartbeat using the Daubechies-4 (db4) wavelet. The decomposition produces one approximation coefficient group (cA4) and four detail coefficient groups (cD4, cD3, cD2, and cD1), from which wavelet-based statistical features are extracted.
Figure 3. Four-level discrete wavelet decomposition of a representative ECG heartbeat using the Daubechies-4 (db4) wavelet. The decomposition produces one approximation coefficient group (cA4) and four detail coefficient groups (cD4, cD3, cD2, and cD1), from which wavelet-based statistical features are extracted.
Preprints 245923 g003
Figure 4. Subject-level distribution of the four heartbeat classes across the 43 subjects included in the study. The heatmap uses a logarithmic transformation, log 10 ( n + 1 ) , to represent differences in class frequency across subjects.
Figure 4. Subject-level distribution of the four heartbeat classes across the 43 subjects included in the study. The heatmap uses a logarithmic transformation, log 10 ( n + 1 ) , to represent differences in class frequency across subjects.
Preprints 245923 g004
Figure 5. Overall performance comparison between Random Forest and XGBoost across the three random seeds under the leave-one-subject-out evaluation protocol.
Figure 5. Overall performance comparison between Random Forest and XGBoost across the three random seeds under the leave-one-subject-out evaluation protocol.
Preprints 245923 g005
Figure 6. Subject-level variability in Macro-F1 for Random Forest and XGBoost across the 43 held-out subjects. For each subject, Macro-F1 was averaged across the three random seeds before plotting.
Figure 6. Subject-level variability in Macro-F1 for Random Forest and XGBoost across the 43 held-out subjects. For each subject, Macro-F1 was averaged across the three random seeds before plotting.
Preprints 245923 g006
Figure 7. Row-normalized confusion matrices for Random Forest and XGBoost, averaged over the three random seeds. Rows represent the true heartbeat classes and columns represent the predicted classes.
Figure 7. Row-normalized confusion matrices for Random Forest and XGBoost, averaged over the three random seeds. Rows represent the true heartbeat classes and columns represent the predicted classes.
Preprints 245923 g007
Table 1. Mapping of ECG annotation symbols to the four heartbeat classes.
Table 1. Mapping of ECG annotation symbols to the four heartbeat classes.
Class Annotation symbols Description
N N, L, R, e, j Normal and bundle branch beats
S A, a, J, S Supraventricular ectopic beats
V V, E Ventricular ectopic beats
F F Fusion beats
Table 2. Overall pooled classification performance across 100,693 heartbeat predictions.
Table 2. Overall pooled classification performance across 100,693 heartbeat predictions.
Model Seed Accuracy Balanced Accuracy Macro-F1 Weighted-F1
RF 42 0.9143 0.4566 0.4306 0.9051
RF 123 0.9206 0.4655 0.4411 0.9109
RF 2026 0.9286 0.4649 0.4522 0.9175
XGBoost 42 0.8577 0.5068 0.4832 0.8874
XGBoost 123 0.8604 0.5321 0.4937 0.8873
XGBoost 2026 0.8665 0.5341 0.5082 0.8960
Table 3. Mean class-wise F1-score across three random seeds.
Table 3. Mean class-wise F1-score across three random seeds.
Heartbeat Class RF XGBoost
N 0.9577 0.9245
S 0.0466 0.2316
V 0.7609 0.8120
F 0.0000 0.0120
Table 4. Mean and standard deviation of subject-level performance across 43 LOSO folds.
Table 4. Mean and standard deviation of subject-level performance across 43 LOSO folds.
Model Seed Balanced Accuracy Macro-F1
Mean SD Mean SD
RF 42 0.6213 0.2405 0.3968 0.1347
RF 123 0.6409 0.2367 0.4078 0.1376
RF 2026 0.6374 0.2369 0.4028 0.1280
XGBoost 42 0.7327 0.2178 0.4314 0.1373
XGBoost 123 0.7349 0.2291 0.4297 0.1384
XGBoost 2026 0.7333 0.2113 0.4281 0.1347
Disclaimer/Publisher’s Note: The statements, opinions and data contained in all publications are solely those of the individual author(s) and contributor(s) and not of MDPI and/or the editor(s). MDPI and/or the editor(s) disclaim responsibility for any injury to people or property resulting from any ideas, methods, instructions or products referred to in the content.
Copyright: This open access article is published under a Creative Commons CC BY 4.0 license, which permit the free download, distribution, and reuse, provided that the author and preprint are cited in any reuse.