October 20, 2026
Algorithm for Atrial Fibrillation Detection in Resting Electrocardiogram
Algorithm for Atrial Fibrillation Detection in Resting Electrocardiogram
Vinícius dos Santos Bandoch; Ricardo Janes
DOI: 10.22167/2675-6528-202603532
Article derived from a Course Conclusion Work (TCC), with content based on the student’s original work and adapted to the editorial format of the E&S Magazine with the support of the ResumeAI tool, an artificial intelligence solution developed by Instituto Pecege for textual synthesis and organization.
Summary
Atrial fibrillation (AF) represents the most common cardiac arrhythmia in clinical practice and a global public health problem, associated with an increased incidence of severe cardiac events and higher mortality, especially in older individuals. A machine learning algorithm was developed for the detection of AF in resting electrocardiograms (ECG). The objective was to create a two-stage system, combining anomaly detection with respect to the normal electrophysiological pattern and supervised classification of ECG signals for the presence of AF. Additionally, the performance of different versions of the classification stage was compared, with and without the integration of the anomaly score as a global metric of deviation from normality. ECG signals from the PhysioNet repository were used, pre-processed by filtering, segmentation into windows, and extraction of statistical and heart rate variability features. The K-Nearest Neighbors (KNN) algorithm was the basis for the “one-class” anomaly detector and for the supervised classifiers (standard, with concatenated and weighted score). The results indicated that the supervised model with the concatenated anomaly score showed the best overall performance, demonstrating a superior balance between precision and sensitivity. The integration of the anomaly score as an additional variable contributed positively to the class separation capability, while feature weighting did not generate consistent gains. It was concluded that the combination of anomaly detection and supervised classification is a viable and effective strategy for the diagnosis of AF, with the form of information integration being determinant for performance.
Keywords: Machine Learning; Classification; Anomaly detection; Electrocardiogram; Atrial fibrillation.
1. Introduction
Atrial fibrillation (AF) is the most prevalent cardiac arrhythmia in clinical practice, constituting a global public health problem. Its presence is associated with a significant increase in the incidence of severe cardiac events, such as stroke (CVA), and higher mortality rates among affected individuals. Population aging exacerbates this issue, as AF predominantly affects individuals in later stages of adulthood (Li et al., 2019). This condition is generated by electrophysiological alterations that result in rapid and disorganized atrial electrical activity, potentially reaching heart rates exceeding 350 beats per minute (Moreira, J. A. C., 2024).
In the current clinical context, the detection of atrial fibrillation is often initiated through a resting electrocardiogram (ECG). This examination provides a graphical representation of cardiac function, where a healthy patient exhibits stable and periodic behavior. In contrast, a patient with AF tends to present inconsistent signs, notably due to the irregularity of R-R intervals and the absence of organized atrial activity (Cintra et al., 2025). However, the mere observation of cardiac disorganization on the ECG is not sufficient to characterize AF, as several other cardiac arrhythmias can present similar and equally harmful behaviors to health. This ambiguity requires the performance of additional tests, which can delay the diagnostic process and, consequently, the start of adequate treatment.
In this scenario, machine learning (ML) emerges as a promising area of artificial intelligence, dedicated to the development of computational techniques that allow algorithms to acquire knowledge autonomously (Monard and Baranauskas, 2003). ML algorithms are capable of performing classification and prediction functions, making decisions based on patterns identified in large volumes of data. The improvement of these computational tools has impacted various areas of medicine, with cardiology standing out as a field of intense application, especially in the creation of algorithms for the detection of cardiovascular diseases and in the improvement of electrocardiographic diagnoses (Paixão et al., 2022).
The application of machine learning algorithms can, therefore, offer valuable assistance in differentiating between normal ECG patterns, patterns associated with atrial fibrillation, and those related to other cardiac conditions. This distinction capability is crucial for overcoming the limitations of traditional diagnosis, which often requires multiple tests and can lead to delays. The use of ML techniques allows for a more efficient and accurate analysis of ECG signals, potentially accelerating the diagnosis and treatment of AF.
Given the need to improve the detection of atrial fibrillation and mitigate current diagnostic challenges, the present work proposes the development of a computational algorithm for detecting atrial fibrillation in resting electrocardiogram signals, based on two specific steps built using the K-Nearest Neighbors (KNN) algorithm: “one-class” anomaly detection and supervised AF classification. In addition to the construction of the algorithms, the study seeks to evaluate the impact caused by the incorporation of the anomaly metric (score) on the classification results.
2. Material and Methods
This study was characterized as an applied research, with a computational methodological approach, focused on the development of a machine learning algorithm. The system was implemented using the Python language, with the Anaconda distribution and the Spyder development environment. The libraries used included WFDB for manipulation of physiological signals from PhysioNet, NumPy for numerical operations, Matplotlib for visualization, Pandas for data manipulation, Scikit-Learn for the KNN algorithm and metrics, NeuroKit2 for ECG signal processing, and SciPy for digital filtering.
The electrocardiogram (ECG) signals were obtained from the public repository PhysioNet, specifically from the “MIT-BIH Normal Sinus Rhythm Database” and “MIT-BIH Atrial Fibrillation Database” datasets, containing records of normal ECG and with atrial fibrillation (AF). To optimize execution time, the records were accessed locally. The files, with varying durations, were temporally segmented into windows of 180 seconds. To improve signal quality, a fourth-order Butterworth digital band-pass filter was implemented via SciPy, acting on frequencies between 0.5 Hz and 40 Hz to attenuate noise (Ahmed and Al-Obaidi, 2022).
One method detected the R peaks within each 180-second window, generating an R-R interval vector. From these, a set of statistical and heart rate variability (HRV) features was extracted (Souza et al., 2022). Variables such as RMSSD and Sample Entropy (Nayak et al., 2023) were duplicated for implicit weighting. The 180-second base window was segmented into 50-second sub-windows, with a 10-second shift, generating a feature vector for each sub-window. These vectors were grouped into a feature matrix for model input.
The algorithm’s architecture was composed of two stages. The first consisted of anomaly detection using the K-Nearest Neighbors (KNN) algorithm in the “one-class” approach. The normality pattern was established from a set of normal ECG data. The normal signal matrices were subjected to Z-score normalization. The defined hyperparameters were: k equal to 7 neighbors and Euclidean distance (Da Silva, 2025). The anomaly threshold was set at the 90th percentile of the mean distances.
The second stage involved the implementation of supervised KNN classifiers for AF detection. The “simple” model was developed independently of the anomaly score, with k equal to 9 neighbors and Mahalanobis distance. One variation integrated the anomaly score by concatenation as a new variable, maintaining the same hyperparameters. Another version implemented anomaly score weighting, where the weighted feature (x’) was calculated as x * (1 + α * s), with α being a scaling factor and s the anomaly score, and the distance metric changed to Manhattan.
To evaluate the consistency of the models, a test automation mechanism was implemented, performing 50 runs of the algorithm with new record distributions in the training, validation, and test bases. The ideal classification threshold was determined by a procedure that selected candidates based on lower sensitivity loss (recall), maximum acceptable false positive rate (FPR), and distance from the ideal point on the ROC curve. The final threshold was selected by the highest F1 score value, using the validation base to avoid overfitting.
To monitor the algorithm’s robustness, a failure detection logic was implemented. “Moderate failure” was considered when the FA class sensitivity was below 0.5 and the AUC value was below 0.7. “Critical failure” was defined by FA class sensitivity equal to 0, zero true positives, and AUC below 0.5. At the end of the executions, detailed reports in .xlsx format were generated, containing parameters and consolidated results in statistical summaries, including mean, standard deviation, minimum, and maximum values of the main metrics for each model.
3. Results and Discussion
The initial phase of the study involved loading and processing electrocardiogram (ECG) records, where significant limitations related to remote access to the PhysioNet repository databases were identified. Direct file reading over the internet proved sensitive to variations in connection quality and speed, resulting in long execution times. To optimize the process and ensure algorithm efficiency, the strategy of storing ECG records locally on the system disk was adopted. This modification resulted in a substantial reduction in execution time, from several minutes to a few seconds per run, highlighting the importance of data management for system performance.
After local data loading, the previously described preprocessing steps were applied, which included filtering the signals to remove noise and extracting the R-R intervals in 180-second windows. Subsequently, these signals were segmented into 50-second sub-windows, from which the feature vectors were calculated. These vectors, which represent the physiological and statistical quantities of cardiac function, were organized into feature matrices, serving as standardized input for the anomaly detection and supervised classification models. This process was consistently applied to all ECG recordings, both normal and with atrial fibrillation, ensuring uniformity in data preparation.
To evaluate the robustness and consistency of the developed models, the complete algorithm flow was executed fifty times. Each of these executions used a different distribution of records in the training, testing, and validation bases, allowing for a comprehensive analysis of the algorithm’s performance variability and stability across various data scenarios. This validation approach based on multiple executions with different data combinations is crucial to ensure the reproducibility of experiments and the generalization of the obtained results.
Results of one-class KNN-based anomaly detection
The anomaly detection stage was implemented using the K-Nearest Neighbors (KNN) detector in the “one-class” approach, which focuses on establishing a pattern of physiological normality from normal ECG data. For this phase, the algorithm was configured with a number of neighbors (k) equal to seven and employed the Euclidean distance metric. The anomaly threshold was established based on the ninetieth percentile of the distance scores obtained in the normal training set, classifying points that exceeded this value as anomalous.
The performance evaluation of the anomaly detector, conducted through multiple runs with different data combinations, revealed an average false positive rate (FPR) of 0.184 for normal signals. This means that approximately eighteen percent of signals considered normal were erroneously classified as anomalies. On the other hand, the average anomaly detection rate in signals with atrial fibrillation (recall) was 0.667, indicating that about two-thirds of signals with AF were correctly identified as anomalous.
These results suggest that the model possesses a moderate capacity to distinguish patterns, being effective in identifying most AF signals as anomalous, although with a notable proportion of false positives in normal signals. The choice of the anomaly threshold proved to be crucial, directly influencing the balance between sensitivity and the false positive rate. This flexibility allows the detector’s behavior to be adjusted according to clinical priorities, where minimizing false negatives or false positives may be more desirable. In its function, this step acts as an initial filter, identifying deviations from normality that, while not exclusive to AF, complement the analysis of the supervised classifier by providing an additional measure of signal irregularity.
Results of the standard supervised KNN classifier
Following the methodological flow, the performance of the basic supervised classification model was evaluated, which operated without the integration of the anomaly score. This KNN classifier was configured with nine neighbors (k = 9) and used the Mahalanobis distance metric. The choice of this metric is justified by its suitability in scenarios with correlated variables, such as the physiological and statistical characteristics of the R-R intervals, which illustrate the dispersion of values and, therefore, present redundancy. The Mahalanobis distance helps mitigate this redundancy by considering the inverse covariance matrix.
The performance indicators for the standard supervised classifier were calculated based on two classification threshold scenarios: a fixed threshold of 0.5 and an adaptive threshold selected by an optimized procedure. For the fixed threshold, the average accuracy observed was 0.830857, the average precision reached 0.881264, the average sensitivity was 0.774729, and the average F1 score recorded 0.819141. These values reflect the model’s ability to correctly identify the presence of atrial fibrillation, with relatively high precision, but with room for improvement in detecting all positive cases.
When employing the chosen threshold, which seeks to optimize the balance between sensitivity and precision, the standard supervised model presented an average accuracy of 0.832448. The average precision was 0.867888, the average sensitivity reached 0.797605, and the average F1 score was 0.824154. Comparing with the fixed threshold, the adaptive threshold resulted in a slight improvement in the F1 score, indicating a better balance between the metrics. Although the fixed threshold demonstrated higher precision, the adaptive threshold favored sensitivity, which is often desirable in clinical contexts to minimize false negatives.
Overall, the standard supervised classifier demonstrated consistent performance across multiple runs, evidencing its stability even in the absence of additional information provided by the anomaly score. The ability to satisfactorily identify patterns associated with atrial fibrillation was confirmed, with the choice of classification threshold influencing the trade-off between precision and sensitivity. The slight improvement in the F1 score with the adaptive threshold highlights the importance of adjusting the decision boundary to optimize the detection of positive cases, a critical aspect in the diagnosis of medical conditions.
Results of the supervised classifier with concatenated anomaly score
The third stage of the study explored the integration of the anomaly score as a new variable in the feature matrices of the supervised classifier. This approach aimed to incorporate a global measure of deviation from the normality pattern, complementing the local information derived from the R-R intervals. The configuration of this model maintained the hyperparameters of the standard supervised classifier, using nine neighbors (k = 9) and the Mahalanobis distance metric, allowing for a direct comparison of the impact of concatenating the anomaly score on performance.
For the classifier with concatenated anomaly score and a fixed threshold of 0.5, the average performance metrics were: Accuracy of 0.837202, Precision of 0.881893, Sensitivity of 0.790029, and F1-score of 0.827564. These results indicate robust performance, with Accuracy and F1-score slightly higher compared to the standard supervised model with a fixed threshold. The concatenation of the anomaly score contributed to a more balanced classification between precision and sensitivity, integrating both the statistical metrics of the R-R intervals and a global signal irregularity indicator.
With the chosen threshold, the supervised model with concatenated anomaly score presented an average accuracy of 0.836232, precision of 0.872067, sensitivity of 0.799059, and F1 score of 0.827335. It is observed that, with the adaptive threshold, sensitivity had a small increase, while precision and F1 score remained at high levels. The integration of the anomaly score as an additional variable proved to be an effective strategy for improving the class separation capability, resulting in enhanced overall classifier performance.
Weighted supervised KNN classifier results
The latest version of the classifier model explored a different approach to integrate the anomaly score, using it as a weighting factor for the original features. This mathematical weighting, defined by the expression x’ = x * (1 + α * s), where x’ is the weighted feature, x the original, α the scaling factor (0.65), and s the anomaly score, aimed to alter the geometry of the feature space to facilitate separation between classes. The hyperparameters were kept consistent with the original supervised model, except for the distance metric, which was changed to Manhattan due to observed instabilities with the Mahalanobis distance.
The evaluation of the supervised model’s performance, weighted with a fixed threshold of 0.5, revealed an average accuracy of 0.814007, precision of 0.822219, sensitivity of 0.816727, and an F1 score of 0.812663. These results indicate a balanced performance between precision and sensitivity, with relatively close values. However, compared to the model with the concatenated score, the accuracy and F1 score metrics were slightly lower, suggesting that feature weighting, while theoretically promising, did not result in consistent performance gains in this specific scenario.
With the chosen threshold, the weighted supervised model presented an average accuracy of 0.805181, precision of 0.825981, sensitivity of 0.798654, and an F1 score of 0.800962. Although the fixed threshold slightly favored sensitivity and F1 score, the selected threshold provided a small increase in precision. The instability observed with Mahalanobis distance, caused by the alteration of the feature space geometry due to weighting, may have affected the discrimination capacity between classes, which led to the adoption of Manhattan distance for this model version.
In summary, the incorporation of the anomaly score as a weighting factor modified the geometry of the feature space, making the classifier more balanced in terms of precision and sensitivity compared to the simple supervised model. However, the results did not show consistent performance gains compared to the standard supervised model, especially regarding the F1 score. This behavior suggests that, despite being able to detect a larger quantity of true positive cases, the weighting of the variables may introduce distortions in the feature space, negatively impacting the overall balance of the model.
Comparison between models
The direct comparative analysis between the three supervised models — the standard one, the one with concatenated anomaly score, and the weighted one — was performed considering both a fixed classification threshold of 0.5 and an adaptive threshold selected for each run. This comparison allowed for a comprehensive evaluation of the impact of different anomaly score integration strategies on the overall performance of the algorithms. Accuracy, precision, sensitivity, and F1 score metrics were the main indicators used for this evaluation, providing a clear view of the advantages and disadvantages of each approach.
Considering the fixed classification threshold of 0.5, the supervised model with concatenated anomaly score presented the best overall performance. It achieved an average accuracy of 0.837202, precision of 0.881893, recall of 0.790029, and an F1 score of 0.827564. In contrast, the standard supervised model obtained an accuracy of 0.830857, precision of 0.881264, recall of 0.774729, and an F1 score of 0.819141. The weighted model registered the lowest values in this scenario, with an accuracy of 0.814007, precision of 0.822219, recall of 0.816727, and an F1 score of 0.812663. This data highlights the superiority of concatenating the anomaly score.
When the best threshold elected for each run was used, the supervised model with concatenated anomaly score maintained its leading position, presenting an average accuracy of 0.836232, precision of 0.872067, sensitivity of 0.799059, and F1 score of 0.827335. The standard supervised model, in turn, registered an accuracy of 0.832448, precision of 0.867888, sensitivity of 0.797605, and F1 score of 0.824154. Again, the weighted model obtained the most modest results, with accuracy of 0.805181, precision of 0.825981, sensitivity of 0.798654, and F1 score of 0.800962. The consistency of these results reinforces the effectiveness of concatenation.
The comparative analysis of the results demonstrated that the supervised model with concatenated anomaly score exhibited the best overall performance among all evaluated configurations. This superiority was consistent in both the fixed classification threshold scenario and the elected threshold scenario, especially concerning the F1 metric, which represents a crucial balance between precision and recall. The standard supervised model presented a close, but slightly inferior performance across all metrics, indicating that the inclusion of the anomaly score as an additional feature contributes positively to the class separation capability.
On the other hand, the weighted supervised model presented a distinct behavior, with greater sensitivity in the fixed threshold scenario, but with a reduction in accuracy and F1 score metrics in both analyzed scenarios. This result suggests that, although the model was able to detect a larger quantity of true positive cases, the weighting of the variables may have caused distortions in the feature space, negatively impacting the model’s overall balance. In summary, concatenating the anomaly score as an additional variable proved more effective than using it as a weighting factor, underscoring that the way information is integrated is a determining factor for the algorithm’s final performance.
Discussion of Results
The obtained results confirm the viability and effectiveness of using a two-stage algorithm for the detection of atrial fibrillation: anomaly detection and supervised classification. This combined architecture has proven capable of successfully distinguishing between physiologically anomalous patterns, patterns specifically associated with atrial fibrillation, and normal ECG patterns. The two-stage approach allows for a more granular analysis, where the initial anomaly detection acts as a filter, identifying deviations from normality that are then refined by supervised classification for a more specific AF diagnosis.
The incorporation of the anomaly score as an additional variable in the supervised classifier proved to be a particularly effective strategy. This global measure of deviation from the normality pattern complemented the local features extracted from the R-R intervals, enriching the set of information available to the algorithm. The results indicate that this approach contributed significantly to the improvement of the classifier’s performance, especially regarding the balance between precision and sensitivity, crucial aspects for diagnostic accuracy in clinical contexts.
In contrast, the supervised model’s weighting strategy, while theoretically promising, resulted in a geometric modification in the feature space that amplified the distances between normal instances and those with AF. However, this alteration led to distortions in the feature space, which, in turn, reduced the effectiveness of the module responsible for selecting the best classification thresholds. Consequently, no evident performance gain was observed by the algorithm with this approach, suggesting that direct manipulation of the feature space geometry can be counterproductive in certain scenarios.
In summary, the study demonstrated that the combination of anomaly detection and supervised classification is a robust approach for diagnosing atrial fibrillation in resting ECGs. The integration of the anomaly score as an additional feature proved to be the most effective strategy, improving the balance between classifier accuracy and sensitivity. On the other hand, feature weighting, although aimed at optimizing separation, introduced instabilities that compromised performance. These findings reinforce the importance of careful selection of information integration techniques to maximize the predictive capacity of machine learning algorithms in biomedical applications.
4. Conclusion
This study sought to develop a two-stage computational algorithm for the detection of atrial fibrillation in resting electrocardiogram signals, combining “one-class” anomaly detection with supervised classification, and evaluated the impact of integrating the anomaly score on the results. It was found that the two-stage architecture, composed of a KNN anomaly detector and a supervised classifier, proved to be a viable and effective strategy for distinguishing physiologically anomalous patterns from those specifically associated with atrial fibrillation. The results indicated that the supervised model with the concatenated anomaly score exhibited the best overall performance, with a superior balance between precision and sensitivity, demonstrating that the inclusion of this global measure of deviation from normality as an additional feature enriched the information set for the algorithm. In contrast, weighting the features with the anomaly score did not yield consistent performance gains, suggesting that this approach introduced distortions in the feature space that compromised the model’s effectiveness. The main contribution of this work lies in demonstrating that the way anomaly information is integrated is determinant for the algorithm’s predictive capability, offering a technical advancement for the more accurate diagnosis of atrial fibrillation.
Among the study’s limitations, the dependence on the dataset used and the model’s sensitivity to the choice of hyperparameters were identified, such as the distance metric, the number of neighbors, and the classification threshold, factors that may restrict the algorithm’s generalization capability in different clinical scenarios. For future studies, it is suggested to evaluate the model on larger databases, with an expanded number of records of normal ECG and atrial fibrillation, in addition to increasing the number of runs in the variability analysis procedure to verify the algorithm’s stability in high-information density scenarios. Additionally, it is recommended to explore the use of adaptive weighting methods for defining the feature set, as well as investigate other ways of integrating the anomaly score, considering the sensitivity of KNN-based models to feature space modeling.
Bibliographic References
Ahmed, A., Al-Obaidi, M. 2022. A review of ECG signal filtering approaches. Global Journal of Engineering and Technology Advances. Volume 11. p. 93 a 97. 2022. Disponível em: <https://www.researchgate.net/publication/361652803_A_review_of_ECG_signal_filtering_approaches>
Cintra, F. D., Pisani, C. F. et al. 2025. Diretriz Brasileira de Fibrilação Atrial – 2025. In: Arquivos Brasileiros de Cardiologia. Volume 122, Edição 9. 2025. Disponível em: https://www.scielo.br/j/abc/a/jWrKHyPRYYh7dXZR94nJcGp/?format=pdf&lang=pt&ilang=e
da Silva, J. P. S., 2025. K-Nearest Neighbors para Detecção de Anomalias e Manutenção Preditiva em Sistemas de Abastecimento Hídrico. Tese de Doutorado em Engenharia Elétrica e de Computação, UFRN, Natal, Rio Grande do Norte, Brasil. Disponível em: <https://repositorio.ufrn.br/server/api/core/bitstreams/68f81a9f-0923-4a83-a9aa-649d5d45f640/content>
Li, H., Song, X., Liang, Y. et al. 2019. Global, regional, and national burden of disease study of atrial fibrillation/flutter, 1990–2019: results from a global burden of disease study. BMC Public Health, volume 22. Disponível em: <https://doi.org/10.1186/s12889-022-14403-2>
Monard, M. C, Baranauskas, J. A. 2003. Conceitos sobre Aprendizado de Máquina. p. 89-114. Rezende, S. O, In Sistemas Inteligentes – Fundamentos e Aplicações, Editora Manole, Barueri, São Paulo, Brasil. Disponível em: <https://dcm.ffclrp.usp.br/~augusto/publications/2003-sistemas-inteligentes-cap4.pdf>
Moreira, J. A. C., et al., 2024, Fibrilação Atrial e Flutter Atrial. p. 283-288. In: Cardiologia: Teoria e Prática. Edição 14. Editora Pasteur, 2024. Disponível em: <https://sistema.editorapasteur.com.br/uploads/pdf/publications_chapter/FIBRILAÇÃO%20ATRIAL%20E%20FLUTTER%20ATRIAL-b5f186d2-d53c-4e59-b010-4b4740cacc48.pdf>
Nayak, S. K., Pradhan, B. et al. 2023. A Review of Methods and Applications for a Heart Rate Variability Analysis. p. 433. In: Algorithms. Volume 16, Edição 9. 2023. Disponível em: https://www.mdpi.com/1999-4893/16/9/433
Paixão, G. M. de M, Santos, et al., 2022. Machine Learning na Medicina: Revisão e Aplicabilidade. Sociedade Brasileira de Cardiologia. Arq Bras Cardiol. Disponível em: <https://www.scielo.br/j/abc/a/WMgVngCLbYfJrkmC65VFCkp/?format=pdf&lang=pt>
Souza, P. M, Araújo, C. R. V. et al. 2022. Variabilidade da frequência cardíaca: dos cuidados no registro à aplicabilidade ao exercício físico. p. 365-380. In: Revista Brasileira de Fisiologia do Exercício. Volume 21, Edição 6. 2022. Disponível em: <https://convergenceseditorial.com.br/index.php/revistafisiologia/article/view/5411/8441>
Article originating from the Final Course Project of the Specialization in Data Science and Analytics of the MBA USP/Esalq
To learn more about the course, click here and access the MBX Academy platform