1. Introduction
Atrial fibrillation (AF) is the most prevalent sustained arrhythmia in clinical practice, characterized by rapid and irregular atrial contractions [
1]. Globally, over 37 million adults are affected by AF, with a continuously rising prevalence driven by population aging [
2]. This condition significantly increases the risk of cardioembolic stroke, and is recognized as a leading preventable cause of this life-threatening complication [
3,
4]. The clinical presentation of AF is highly heterogeneous. Paroxysmal AF, in particular, manifests as short, unpredictable episodes with subtle or even asymptomatic manifestations in the early stage, making it easily missed during standard short-duration electrocardiogram (ECG) examinations. Therefore, long-term continuous cardiac monitoring is critical for accurate and timely AF diagnosis [
5].
Traditional Holter monitors, the gold standard for long-term ECG recording, are limited to a 24–48 h recording window, which often fails to capture brief paroxysmal AF episodes. These devices are also bulky and uncomfortable for patients, interfering with daily activities. In recent years, patch-type and wearable ECG devices have emerged as promising tools for AF screening. Their compact, lightweight design enables continuous monitoring for up to 14 days, making them well-suited for community-based screening and long-term home monitoring [
6,
7]. These devices are typically integrated into a cloud-based intelligent AF monitoring system, whose general workflow is illustrated in
Figure 1. Such systems realize end-to-end closed-loop management from long-term ECG signal acquisition, AI-powered automated AF detection, to remote clinical intervention, providing strong technical support for early AF screening and diagnosis. In addition to continuous long-term monitoring devices, another important class of ECG monitors designed for intermittent but repeated short-term measurements (e.g., approximately 1 min recordings, once or twice daily), akin to home blood pressure monitoring, has emerged. These devices have proven particularly effective in detecting brief and isolated paroxysmal AF episodes [
8]. By integrating into a patient’s daily routine, they offer a low-burden alternative for long-term surveillance and can also be incorporated into the intelligent monitoring paradigm.
However, the massive volume and inherent complexity of data from both continuous and intermittent wearable devices pose significant challenges for automated AF detection algorithms. The inherent signal-level constraints of wearable ECG acquisition further compound these challenges. Dynamic recordings obtained during free-living conditions are inevitably corrupted by motion artifacts, myoelectric noise, and baseline wander, which can obscure or mimic the subtle electrocardiographic signatures that are critical for reliable AF diagnosis, particularly the disappearance of P waves [
9]. Consequently, denoising algorithms designed for wearable dynamic ECG have become an essential prerequisite for accurate rhythm analysis. In parallel, the limited computational resources and strict power budgets of battery-operated wearable platforms impose uncompromising demands on model efficiency. Practical algorithms must operate within tight memory footprints and energy envelopes, making the compression of deep learning architectures a pivotal consideration for on-device deployment [
10]. Collectively, these observations highlight that an effective wearable AF screening algorithm must not only be accurate and generalizable, but also inherently robust to real-world noise and computationally lightweight.
Generally, there are two main approaches for AF detection: traditional machine learning methods and deep learning-based methods.
Traditional machine learning methods often rely on hand-crafted features extracted from ECG signals. For instance, Datta et al. [
11] developed a multi-layer binary classifier using hand-crafted statistical, morphological, and heart rate variability features from single-lead ECG signals. However, manual feature extraction is time-consuming, has limited representation capacity for complex data, and performs poorly in noisy and high-variability scenarios. Similarly, Athif et al. [
12] proposed a rule-based algorithm using statistical and morphological features, yet it only achieved a sensitivity of 77.5% and demonstrated poor adaptability to low-quality single-lead signals.
In contrast, deep learning-based methods aim to automatically learn features and capture temporal dependencies. Kiranyaz et al. [
13] introduced a 1D convolutional neural network (1D-CNN) model for patient-specific ECG classification, which effectively captured local spatiotemporal features; however, it failed to learn long-range temporal dependencies associated with AF. To address sequence modeling, Schuster et al. [
14] proposed a bidirectional recurrent neural network (RNN) structure to process sequence information. Nevertheless, this approach suffered from vanishing gradient problems as sequence length increases, making it ineffective for long-duration AF signals. Shewalkar et al. [
15] compared the performance of long short-term memory (LSTM) and gated recurrent unit (GRU) networks for AF detection. Although these models captured partial temporal dependencies, their accuracy degraded significantly when modeling ultra-long ECG signals. More recently, the Transformer architecture proposed by Vaswani et al. [
16] used global self-attention to capture intra-sequence relationships. Despite its effectiveness, a pure Transformer model had high computational complexity, which hindered its deployment on resource-constrained wearable devices.
To address the aforementioned limitations, this study proposed a RT-AFNet architecture for automatic AF detection from ECG signals. This architecture effectively integrated the strengths of Residual Neural Network (ResNet) in local feature extraction and the Transformer self-attention mechanism in long-range dependency modeling. By embedding lightweight self-attention modules into the key layers of the ResNet backbone, it simultaneously captured the local morphological features and global temporal context of ECG signals. To verify the robustness and generalization ability of the model, we conducted experiments on three public AF datasets: China Physiological Signal Challenge 2018 (CPSC2018), PhysioNet/Computing in Cardiology Challenge 2017 (CinC2017), and MIT-BIH Atrial Fibrillation Database (MIT-BIH AF). This research aims to provide a high-accuracy, efficient AF detection solution for wearable ECG devices, supporting the development of early AF screening and long-term monitoring technologies.
The main contributions of this paper are summarized as follows:
Spatiotemporal Joint Representation Learning Framework. We designed a RT-AFNet architecture, which combines the local feature extraction power of a ResNet backbone with the global temporal modeling capability of a lightweight self-attention mechanism. By integrating attention modules in key layers (specifically, Layer 2 and Layer 3) to capture long-range dependencies, which refer to temporal relationships spanning multiple heartbeats (i.e., minute-scale temporal dynamics), and implementing hierarchical feature fusion, we built an end-to-end unified learning framework for ECG-based AF detection.
Multi-Scale Feature Fusion and Adaptive Robust Training Strategy. We introduced a comprehensive multi-scale feature fusion mechanism alongside an adaptive training strategy to enhance the model’s representation capacity and optimize learning dynamics. The fusion module dynamically aggregates global pooling representations, multi-resolution temporal semantics, attention-weighted vectors, and statistical features to accurately map irregular rhythm patterns. Weighted Cross-Entropy (WCE) Loss was used to address class imbalance, a layer-wise learning rate schedule is implemented for different modules, and data augmentation techniques including Gaussian noise addition and random masking were applied to achieve balanced improvement in precision and recall.
Validation of generalization ability based on multi-source datasets. We conducted comprehensive empirical validations of the proposed framework across three diverse public AF datasets. This demonstrates the architecture’s capacity to maintain stable, high-accuracy performance across varying signal qualities and diverse patient populations, thereby verifying its reliability for a wide range of real-world clinical application scenarios.
The remainder of this paper is organized as follows.
Section 2 describes the materials and methods, including the three public AF databases, the preprocessing workflow, and the proposed RT-AFNet architecture.
Section 3 presents the experimental results, covering classification performance, ablation analysis, cross-database generalization, error analysis, and complexity evaluation.
Section 4 discusses the findings, compares RT-AFNet with state-of-the-art methods, and analyzes its behavior on confounding arrhythmias.
Section 5 concludes the paper and outlines directions for future work.
3. Results
3.1. Experimental Configuration
All experiments were performed on a workstation equipped with an AMD Ryzen 7 7735H processor (base clock 3.20 GHz; Advanced Micro Devices, Inc., Santa Clara, CA, USA) and 16 GB of RAM. The system included an NVIDIA GeForce RTX 4060 Laptop GPU with 8 GB of dedicated video memory. It ran on the Windows 11 Home operating system and utilized an NVMe SSD for storage. The models were implemented using Python 3.8 within the PyCharm 2023 development environment, leveraging deep learning frameworks such as TensorFlow 2.11 and PyTorch 2.4.1, together with common libraries including NumPy 1.24.4, scikit-learn 1.3.2, and Transformers 4.46.3. This hardware and software configuration ensured reproducible and efficient experimental runs.
3.2. Quantitative Classification Performance
To comprehensively validate the AF detection performance and generalization capability of our proposed RT-AFNet architecture, we performed systematic verification experiments on three widely used public datasets, namely CPSC2018, CinC2017 and MIT-BIH AF. The five core evaluation metrics were used to quantify the model’s performance for the binary AF vs. Non-AF classification task. The performance results on the three datasets are presented in
Table 2.
On the CPSC2018 and MIT-BIH AF datasets, both of which use standard Lead II, the model achieved F1 scores of 99.76% and 96.20%, respectively. On the CinC2017 dataset, which employs a Lead I equivalent via the AliveCor Kardia device, the model achieved an F1 score of 97.47%. Despite the difference in lead orientation between CinC2017 (Lead I) and the other two datasets (Lead II), the model maintained consistently strong performance across all three without any lead-specific fine-tuning. This cross-lead robustness suggests that RT-AFNet captures lead-invariant features for AF detection: the ResNet backbone extracts local morphological patterns that retain diagnostic waveform characteristics across lead configurations, while the Transformer module models global rhythm irregularity, a temporal property independent of lead orientation. This inherent property is a practical advantage for deployment across heterogeneous wearable ECG devices.
3.3. Confusion Matrix Analysis
To intuitively illustrate the classification performance and misclassification distribution of the model on each dataset, we plotted the confusion matrices for the test sets of CPSC2018, CinC2017, and MIT-BIH AF datasets, as shown in
Figure 4. The matrices quantify the model’s binary classification results for AF and Non-AF categories in terms of true negatives (TN), false positives (FP), false negatives (FN), and true positives (TP). On the CPSC2018 dataset, the model correctly identified 183 Non-AF samples and 241 AF samples, with only 0 FP and 1 FN, reflecting an extremely low misclassification rate for both categories. For the larger-scale CinC2017 dataset consisting of short-term single-lead ECG recordings, the model achieved 2332 TN, 328 TP, 35 FP, and 34 FN, maintaining high classification accuracy in ambulatory ECG monitoring scenarios. On the long-term MIT-BIH AF dataset, a widely recognized challenging benchmark with abundant paroxysmal AF episodes, the model correctly classified 13,984 Non-AF samples and 3731 AF samples, with only 270 FP and 425 FN, demonstrating excellent capability to capture transient AF episodes while minimizing false alarms in long-term continuous monitoring. Across all three datasets, the model consistently exhibited a high true positive rate and true negative rate, with limited false positive and false negative events, verifying its stable and reliable classification performance for AF detection.
3.4. ROC Curve and AUC Evaluation
The receiver operating characteristic (ROC) curves of the proposed model on the test sets of the three datasets are presented in
Figure 5, which further characterizes the model’s overall discriminative ability across different classification thresholds. The ROC curve plots the true positive rate (TPR, sensitivity) against the false positive rate (FPR, 1-specificity) at various decision thresholds, and the area under the ROC curve (AUC) serves as a comprehensive metric for the model’s global classification performance. As shown in
Figure 5, the ROC curves of the model on all three datasets are tightly close to the upper-left corner of the coordinate system, which represents the ideal classification performance with 100% TPR and 0% FPR. The model achieved AUC values of 99.97%, 98.98%, and 98.28% on the CPSC2018, CinC2017, and MIT-BIH AF datasets, respectively, all approaching the perfect value of 1.0. These results further confirm that the proposed model has excellent discriminative power for distinguishing AF from Non-AF ECG signals.
3.5. SHAP-Based Model Interpretability
Despite the superior classification performance achieved by deep learning models, they are often criticized as “black boxes” due to their multi-layer non-linear structure, which makes the model’s decision-making process difficult for humans to understand. In clinical practice, the interpretability of a diagnostic model is as critical as its diagnostic accuracy, as it can help clinicians understand the basis of the model’s decisions, enhance trust in the algorithm, and provide auxiliary evidence for clinical decision-making. To address this issue, we used the SHapley Additive exPlanations (SHAP) method, a game-theoretic approach that provides a unified framework for interpreting the predictions of any machine learning model. Specifically, SHAP assigns a unique Shapley value to each input feature, which quantifies the additive contribution of that feature to the model’s final prediction. A positive Shapley value indicates that the feature has a positive contribution to the model’s prediction of AF, while a negative value indicates a negative contribution towards AF classification (i.e., supporting the prediction of Non-AF). In this study, we used the gradient explainer to calculate the Shapley values for each time step of the input ECG signals, enabling us to interpret the model’s decision-making process at the patient level.
The patient-level interpretation results of the model on representative AF and Non-AF samples from the three datasets are visualized in
Figure 6. For the AF samples from all three datasets (
Figure 6a,c,e), the high-contribution regions highlighted by Shapley values were mainly concentrated in the areas corresponding to the absence of P waves and irregular RR intervals, which are the gold-standard diagnostic criteria for AF in clinical practice. In contrast, for the Non-AF (normal sinus rhythm) samples (
Figure 6b,d,f), the regions with high Shapley values were aligned with regular P waves, stable PR intervals, and normal QRS complexes, which are the typical characteristics of normal sinus rhythm. These observations demonstrate that the decision-making basis of the proposed model is highly consistent with clinical AF diagnostic rules, rather than relying on spurious correlations or noise in the ECG data. This patient-level interpretability not only verifies the rationality of the model’s feature learning, but also provides intuitive visual evidence for clinicians to verify the model’s diagnostic results.
3.6. t-SNE Feature Visualization
t-SNE is a widely adopted non-linear dimensionality reduction technique that preserves both the local and global structural characteristics of high-dimensional feature data in the low-dimensional embedding space. This enables intuitive visualization of the inter-class separability and intra-class compactness of the features learned by deep models.
To further validate the effectiveness and discriminability of the high-level features learned by the proposed RT-AFNet model, we employed t-SNE to reduce the dimensionality of the deep features extracted from the test set samples of each dataset. The resulting distribution of AF and Non-AF samples in the two-dimensional feature space is visualized in
Figure 7.
For the CPSC2018 dataset shown in
Figure 7a, AF and Non-AF samples form two completely independent, well-separated clusters with negligible overlap in the 2D embedding space, with only a tiny number of outlier samples crossing the inter-class boundary. It is worth noting that the CPSC2018 dataset has the smallest sample size among the three datasets. Since the duration of each original ECG recording in this dataset is relatively short, only one or two valid analysis windows can be segmented from each recording, resulting in a test set with only 425 samples (AF = 242, Non-AF = 183). Even with such a limited sample scale, the model still achieves clear class separation in the feature embedding space. This demonstrates that the proposed model can learn highly discriminative and robust high-dimensional features even in small-sample scenarios, fully reflecting the excellent feature extraction capability of our hybrid architecture.
In contrast, for the CinC2017 dataset shown in
Figure 7b, although AF and Non-AF samples form two relatively distinct main clusters in the embedding space, there is a non-negligible degree of overlap between the two categories. A small number of samples from each class are distributed within the cluster of the opposite category. Despite this partial overlap in the low-dimensional projection, the proposed model still achieved excellent and stable classification performance on this dataset. This phenomenon indicates that the model has learned complex non-linear decision boundaries in the original high-dimensional feature space, which can accurately distinguish AF and Non-AF samples even when their low-dimensional embeddings are not fully separated. These results further verify the strong non-linear feature modeling capability of our RT-AFNet framework.
For the MIT-BIH AF dataset shown in
Figure 7c, a widely recognized challenging benchmark for AF detection with abundant long-term paroxysmal AF episodes, AF and Non-AF samples are almost completely divided into two independent, highly separated clusters in the 2D embedding space. Only an extremely small number of outlier samples cross the category boundary. This nearly perfect inter-class separation in the low-dimensional space directly demonstrates that the high-level features learned by the proposed model possess exceptional inter-class discriminability, even for the complex, intermittent, and variable paroxysmal AF signals contained in this long-term ECG recording dataset.
3.7. Ablation Study
To quantify the contribution of each architectural component and validate the design choices of RT-AFNet, we conducted an ablation study on the CinC2017 dataset. Four model variants were evaluated: ResNet-only, Transformer-only, without multi-scale fusion (retaining only average pooling), and without weighted cross-entropy loss (using standard cross-entropy).
Table 3 summarizes the results.
The ResNet-only configuration, which relies primarily on local morphological features, achieved an F1-score of 95.04%, compared to 97.47% for the full model. The Transformer-only configuration, which models global rhythm patterns without detailed waveform analysis, achieved 92.72%. These results demonstrate two points. First, each branch alone provides substantial discriminative power, confirming that both morphological and temporal features carry diagnostic information for AF detection. Second, the combined architecture outperforms either single-branch configuration by 2.43 and 4.75 percentage points in F1-score, respectively, directly validating that morphological analysis and temporal irregularity modeling are complementary and that their synergistic integration constitutes the core advantage of RT-AFNet over methods relying predominantly on a single feature type.
Removing the multi-scale fusion module decreased the AUC by 0.60 percentage points, and replacing the weighted cross-entropy loss with standard cross-entropy reduced it by 0.13 percentage points. Although the full model already achieves strong performance, every ablation variant showed a consistent decrease across all metrics, confirming that each component contributes to the final result. Together, the ablation results validate that all components of RT-AFNet are necessary for its optimal performance, with the integration of ResNet-based morphological feature extraction and Transformer-based temporal dependency modeling serving as the primary performance driver.
3.8. Cross-Database Generalization
To rigorously assess the generalization capability of RT-AFNet across different acquisition systems and patient populations without any dataset-specific retraining, we conducted zero-shot cross-database evaluations. A model trained on one dataset was directly evaluated on the test set of another dataset.
Table 4 summarizes the results for three transfer scenarios forming a complete evaluation cycle across all three datasets.
When trained on CinC2017 (short single-lead recordings from a consumer device) and tested on MIT-BIH AF (long-term clinical recordings), RT-AFNet achieved an F1 score of 95.80%, demonstrating that features learned from consumer-grade short recordings transfer effectively to clinical-grade long-term data. In the reverse direction, MIT-BIH AF to CPSC2018 yielded an F1 score of 94.35%, confirming robust generalization from long-term clinical data to multi-lead clinical recordings. The CPSC2018 to CinC2017 transfer, the most challenging due to limited CPSC2018 training samples, still achieved an F1 score of 84.76%. These results confirm that RT-AFNet learns genuine, dataset-invariant features of AF rather than overfitting to domain-specific artifacts.
3.9. Error Analysis on Confounding Rhythms
To investigate whether classification errors are associated with specific ECG patterns, we conducted a focused error analysis on the MIT-BIH AF test set. Using the original rhythm annotations, we reconstructed fine-grained labels for all test windows, separating atrial flutter (AFL) from the binary AF/Non-AF labels used in training. AV junctional rhythm (J) segments were absent from the test set, as the limited number of J segments in the MIT-BIH AF database (only 32 windows across all records) were all allocated to the training or validation sets under patient-based stratified splitting. The classification results across rhythm types are summarized in
Table 5.
Among AFL segments, 84.07% were misclassified as AF, confirming that atrial flutter with variable AV block represents a significant challenge for binary AF classifiers.
Figure 8 illustrates a representative AFL segment misclassified as AF. The waveform exhibits characteristic saw-tooth flutter waves and irregular ventricular response that closely mimic the disorganized atrial activity of AF, highlighting why even a model combining morphological and temporal analysis can confuse these two rhythms in the absence of explicit AFL training. In contrast, normal sinus rhythm segments were classified with high accuracy (1.89% false AF rate), demonstrating the model’s strong specificity on the most prevalent Non-AF class. These results directly confirm that classification errors are strongly associated with specific ECG patterns, particularly AFL, which is inherently difficult to distinguish from AF in single-lead recordings when AV conduction is variable.
3.10. Complexity Analysis
To evaluate the deployment feasibility of the proposed RT-AFNet in portable and wearable ECG monitoring devices, we conducted a comprehensive computational complexity and inference efficiency analysis.
Table 6 summarizes the architectural specifications of RT-AFNet, measured on a single NVIDIA GeForce RTX 4060 Laptop GPU. The model contains 17.02 M trainable parameters and requires 3.26 GFLOPs for a single 10-s ECG segment (4000 samples at 400 Hz). The model weights occupy 68.27 MB of storage, and the peak GPU memory consumption during inference is 82.40 MB.
Table 7 reports the single-sample inference latency and batch throughput on both GPU and CPU across all three test datasets. The latency distribution is visualized in
Figure 9. The mean GPU latency ranges from 8.76 ms (CPSC2018) to 9.19 ms (CinC2017), corresponding to a real-time factor of over 800× for 10-s ECG segments. On CPU, the mean latency ranges from 29.39 ms to 30.21 ms, still well below the segment duration and suitable for edge devices without GPU acceleration. The GPU throughput exceeds 1000 samples per second on all datasets, confirming that RT-AFNet can process continuous streaming ECG data in real time.
The overall forward propagation complexity of the proposed model is O(n), where n is the input signal length (n = 4000 for 10-s segments at 400 Hz). The complexity breakdown of each core module is summarized in
Table 8.
Unlike pure Transformer architectures, which have a native O(n2) computational complexity that grows quadratically with input signal length, the self-attention module in our hybrid architecture takes as input the feature sequence downsampled by the ResNet backbone. This results in a fixed and greatly reduced sequence length L, making the computational overhead of the self-attention module a constant value independent of the original input signal length n. This design completely avoids the excessive computational complexity and poor scalability of pure Transformer models when processing long-term ECG signals. Both the theoretical analysis and the empirical measurements confirm that the proposed model is inherently lightweight and scalable, providing a solid foundation for deployment on resource-constrained edge devices.
In summary, the experimental results in this section demonstrated that the proposed RT-AFNet model achieved excellent and stable classification performance across three diverse public AF datasets. The confusion matrices confirmed its low misclassification rates, and the ROC curves validated its strong discriminative ability across all decision thresholds. The ablation study verified that each architectural component contributes to the overall performance, with the integration of ResNet-based morphological feature extraction and Transformer-based temporal dependency modeling serving as the primary performance driver. The cross-database evaluations confirmed that the model learns genuine, dataset-invariant features of AF rather than overfitting to domain-specific artifacts. The error analysis on confounding rhythms revealed that classification errors are strongly associated with specific ECG patterns, particularly atrial flutter, which remains inherently difficult to distinguish from AF in single-lead recordings. The SHAP analysis demonstrated that the model’s decision-making process aligns with clinical AF diagnostic criteria, and the t-SNE visualization verified the excellent inter-class separability of its learned high-level features. Moreover, the complexity analysis confirmed that the model is inherently lightweight and scalable, with linear forward propagation complexity O(n), effectively overcoming the quadratic complexity limitation of pure Transformer architectures. Taken together, these results establish the proposed RT-AFNet as a robust, interpretable, and computationally efficient deep learning solution for automated atrial fibrillation screening, well-suited for deployment in portable and wearable ECG monitoring devices.
5. Conclusions
In this study, we proposed RT-AFNet, a novel spatiotemporal hybrid architecture integrating a ResNet backbone, a lightweight Transformer, and multi-scale feature fusion for the robust automated detection of atrial fibrillation (AF). Extensive experiments across three public datasets (CPSC2018, CinC2017, and MIT-BIH AF) demonstrated that RT-AFNet achieved F1-scores of 99.76%, 97.47%, and 96.20%, with corresponding AUC values of 99.97%, 98.98%, and 98.28%, respectively, delivering stable and state-of-the-art performance across all benchmarks. Future work will focus on three directions: extending RT-AFNet to multi-lead inputs for more comprehensive diagnostic information, expanding the framework to multi-class classification for comprehensive arrhythmia differentiation, and developing advanced lightweighting strategies, such as model quantization and network pruning, to further optimize its parameter footprint for ubiquitous deployment on ultra-low-power edge microcontrollers.