Skip to main content
NPJ Systems Biology and Applications logoLink to NPJ Systems Biology and Applications
. 2026 Apr 16;12:72. doi: 10.1038/s41540-026-00702-6

AI-enhanced approaches for personalized cardiac treatment: insights from ECG data

Vibha Tiwari 1,2, Rohit Gupta 1, Akshada Telang 1, Akshra Tiwari 3, Rebakah Geddam 2,4, Muhammad Awais 5, Muhammad Ahmed Khan 6, Hemant Ghayvat 2,7,✉
PMCID: PMC13198540  PMID: 41991936

Abstract

The analysis of drug-induced alterations in the electrocardiogram (ECG) is essential in measuring cardiac safety, but manual analysis is not always accurate enough to identify subtle but important effects. This paper examines how machine learning (ML) models can be used to categorize various pharmacological treatments according to their distinct ECG patterns to establish a platform of individualized therapeutic evaluation. Using the public ECG Effects of Dofetilide, Moxifloxacin, Dofetilide+Mexiletine, Dofetilide+Lidocaine and Moxifloxacin+Diltiazem (ECGDMMLD) database, key electrophysiological features were extracted—including heart rate variability (HRV) and standard cardiac intervals (RR, PR, QT, QRS) to train and compare three different classifiers: XGBoost, Random Forest, and a Support Vector Machine (SVM). The analysis showed that tree-based ensemble techniques were very useful in this task. The XGBoost model had a better classification accuracy of 98.1%, which was closely followed by the random forest at 97.3%. Conversely, the SVM had much lower accuracy, implying that it was not as well adapted to the complexity of the high-dimensional ECG data. These results establish that ML models, particularly XGBoost, can accurately decode complex drug-induced cardiac signatures from ECG data. This work is a powerful demonstration of the proof-of-concept of automated and data-driven analytics integration into clinical processes to enhance drug safety and promote personalized medicine.

Subject terms: Cardiology, Computational biology and bioinformatics, Diseases, Medical research

Introduction

Clinical cardiology would not be the same without the electrocardiogram (ECG), which allows the diagnosis of many cardiac diseases, such as arrhythmias and ischemic heart disease, by examination of its special waveforms1,2. Its use is, however, not limited to routine diagnostics, but also to the imperative area of pharmacological safety surveillance, in which one formidable obstacle continues to exist, namely, the identification of drug-induced cardiotoxicity. This problem is idealized by the prolongation of the QT interval due to the use of drugs, a highly recognized antecedent of Torsades de Pointes (TdP), a fatal arrhythmia that has inspired the pulling out of drugs in the market in large numbers3.

The key issue is the complicated electrophysiology of drug-induced arrhythmias. Although blockage of the hERG potassium channel is an established mechanism, interactions with other ion channels, including calcium or other ion channels, of a given drug, sodium currents, may lead to a significant change in its pro-arrhythmic potential, occasionally in a protective manner3. This causes the QT interval alone to be an inadequate and, in most cases, unstable indicator of the actual cardiac risk. This uncertainty is enhanced by the fact that manual interpretation of ECG is prone to error due to inter-observer variability and is not trustworthy to detect the subtle multi-parameter as such, there exists a differentiation between safe and dangerous compounds, as signatures4. Therefore, there is a compelling need for more precise and objective risk stratification methodologies.

Machine learning (ML) can be used to fill this gap by deploying a disruptive solution to cardiac5. In comparison to manual analysis, ML algorithms will be able to analyze high-dimensional data in order to discover the complex, non-linear relationships that define complex biological systems. This characteristic acts as a crucial ability as it supports the switch from simple biomarkers to the customized and trusted way of assessing cardiac risk, which leads to quicker and much more consistent outputs6.

This study was carried out with the aim of finding the precision of machine learning models in predicting the difference between the effects of drugs on the heart and the raw ECG signals. Figure 1 can be used to summarize the complete research. The dataset used comes with a well-designed drug trial on healthy volunteers and also with public access as the Electrocardiogram Drug-Mediated Multi-Lead Database (ECGDMMLD)7. The multi-lead ECG recordings obtained from this database are used to create a list of sensitive features like heart rate variability (HRV), RR, PR, and QT intervals, and QRS duration, which were later used to train and evaluate three classifiers, i.e., Random Forest, Support Vector Machine (SVM), and XGBoost. The outcomes display that models following a tree-based structure are advantageous for this task. The order of highest accuracy starts with the XGBoost, which showcases 98.1% accuracy, followed by Random Forest and then SVM. This highlights the benefits of using powerful new stage computation methods to understand the complex patterns in ECG introduced by drug induction, which is barely understood with daily measurement techniques. This study proves the role of machine learning in making accurate predictions of heart-related activity from complex signals.

Fig. 1. Complete workflow demonstrating different stages of research.

Fig. 1

This diagram illustrates the sequential pipeline from raw ECG data ingestion through preprocessing, feature extraction, and machine learning classification.

A single heartbeat consists of a complex pattern of electrical events, beginning with the contraction of the atria and ending with the relaxation of the ventricles. These events are displayed as P-wave, QRS complexity, and T-wave4. For more than one-hundred years, doctors have observed the shape of these waveforms, along with their steepness, amplitudes, and time differences, to detect cardiovascular disease. Even though this method is important, it has its own difficulties. The difficulty in reading the ECG signal due to the variability of waves from person to person makes interpretation a time-consuming process and is also dependent on the expertise of the physician. Relying only on the manual interpretation can lead to error and results varying from doctor to doctor, especially when finding small issues or working with a large amount of data8. Early computation methods that used simple rules are effective but were too strict in handling complicated data and continuously changing ECG, which makes it less useful for heart diagnosis9.

With the introduction of the Machine Learning, ECG analysis has been transformed. This technology provided strong resources to address the shortcomings of the manual and rule-based approaches10. proposes a heart monitoring system that is wireless, based on a Hilbert-Huang transformation, which has shown its application on ECG interpretations by using AI. There is a whole variety of ML models that have been experimented with in this area, and each of them has its advantages. Such models as Support Vector Machines (SVMs) were effective in simple classification, such as distinguishing between the normal and arrhythmia heartbeat11. More complex computer techniques, like Artificial Neural Networks (ANNs) can proceed with more complex tasks by being trained based on patterns of big data repositories12. Deep Learning models, in particular Convolutional Neural Networks (CNNs), do a fantastic job at automatically finding meaningful features of the raw ECG waves13. In addition to these endeavors, more recent work has devoted attention to signal quality improvement, such as a sparse code shrinkage algorithm, which is based on empirical mode decomposition, to effectively denoise ECGs14.

Central to the success of many traditional ML classifiers is the critical step of feature engineering. Model predictability is essentially determined by the quality of the feature (vector) on which each heartbeat is modeled. As a result, studies have aimed at deriving clinically meaningful attributes of the ECG signal.

Primary biomarkers resulting in deep insights into the heart activity and critical in the formation of powerful predictive patterns are such key parameters as heart rate variability (HRV) and precise RR, PR and QT intervals and QRS complex.

In this respect, ensemble learning methods have also emerged as a leader in terms of power and strength. One such example is the random Forest, which is a generalized model, admired because of its ability to learn non-linear and complex associations between ECG features and clinical outcomes. The primary advantage of the Random Forest model is that there is a built-in feature importance analysis mechanism in the model, which provides valuable clinical data regarding the underlying factors that affect its predictions, and this makes the model highly interpretable in clinical practice15.

The other powerful approach is known as XGBoost, which is also an ensemble technique and employs gradient-boosted decision trees, and has become one of the best choice models in classification in healthcare. Its structure is very effective in the event of huge and complex data sets that are in frequent use in the ECG analysis task. Also, XGBoost employs sophisticated methods to avoid overfitting and handles missing data effectively, which is why it is a stable and effective tool to use in real-world medical tasks, where data is not always in an ideal form.

Conversely, despite being very good classifiers, SVMs can be somewhat tricky to apply to the analysis of complex ECGs. Tuning of parameters, scaling of data, and feature selection are important to the performance of an SVM. Moreover, their computational needs may be prohibitive with large data sets needed to thoroughly clinically validate them, and this may restrict their scalability in some applications6. The evident advantages of approaches like XGBoost and Random Forest in terms of performance, scalability, and the ability to work with complex data made them the first choice of models to be used in this study.

Although the current literature supports the overall effectiveness of such models in the classification of cardiac signals, there is a certain gap in their use in the prediction of the outcomes of the complex, drug-induced changes in cardiac activity. The intersection of AI, IoT, and biomedical engineering is transforming personalized medicine and real-time monitoring of cardiac activity16. This research paper adds to the literature by comparatively assessing the performance of XGBoost, random forest, and SVM on the Electrocardiogram Drug-Mediated Multi-Lead Database(ECGDMMLD). This study specifically tackles the issue of predicting the effects of treatment through an emphasis on a rich set of features, such as HRV, QT intervals, and other important biomarkers, which can be seen as an approach to illustrate the potential of machine learning to improve personalized medicine and enhance real-time clinical decision-making within a pharmacological setting.

Methodology

Figure 2 shows the analytical structure of this research paper. The suggested methodology adheres to a route that is organized in a way that the raw ECG data are processed to generate predictive information, and the three main stages involved are data preprocessing, feature extraction17, and feature selection.

Fig. 2. Proposed framework for accurate ECG signal analysis and classification.

Fig. 2

The analytical architecture highlights the specific tree-based ensemble approach and baseline models used to predict pharmacological treatment regimens.

Dataset description

This research uses the Electrocardiogram Drug-Medicated Multi-Lead Database (ECGDMMLD)7. The ECGDMMLD database is comprised of data from a randomized, double-blind, 5-period crossover study that evaluated the electrophysiological effects of hERG potassium channel blocking drugs on 22 healthy participants (male and female, aged 18–35), both alone and in combination with late sodium or calcium channel blockers. Across each period, 12 blood samples were collected for pharmacokinetic analysis, synchronized with 12-lead ECG recordings. These five treatment periods are given in Table 1.

Table 1.

Treatment periods, drug combinations, and administration methods with assigned treatment codes

Period Code Drug(s) Administration mode
1 A Dofetilide Alone Oral (after meals)
2 B Lidocaine ( ± Dofetilide) IV (60 min loading + 30 min maintenance)
3 C Mexiletine ( ± Dofetilide) Oral (after meals)
4 D Moxifloxacin ( ± Diltiazem) IV (60 min loading + 30 min maintenance)
5 E Placebo IV (60 min loading + 30 min maintenance)

The directory contains 4211 10-second standard 12-lead ECG segments. The recordings were obtained at several intervals, coinciding with blood draws for pharmacokinetic analysis, resulting in 12 corresponding data points. Additionally, the dataset includes characteristic clinical information for each subject, which includes:

Demographic data: This consists of features like age, sex, height, weight, race, and ethnicity of the subject. It is important to note that these demographic variables were explicitly excluded from the feature arrays used for machine learning. This exclusion ensured the predictive models operated strictly on morphological and electrophysiological properties.

Baseline clinical measurements: This consists of cardiac features like systolic and diastolic blood pressure (SYSBP, DIABP), heart rate, and other vital signs.

ECG-derived parameters: This includes features like automatically extracted measurements from the ECG signals, including QT interval, PR interval, QRS duration, RR interval, and T-wave amplitude, among others.

Data preprocessing

The first step was to do a strict preprocessing of data to convert raw signal data into a clean and structured format that could be analyzed with machine learning. This initial step is important in providing accuracy and reliability of the models. The most important processes were the elimination of noise and correction of baseline wander that removed redundancies and artifacts. The entire preprocessing process is described in Algorithm 1 (the definitions of all symbols in this algorithm are presented in Table 2).

Table 2.

Symbol definitions for Algorithm 1 (data preprocessing)

Symbol Description Type/Dim.
D Raw clinical dataset. Set
S Raw ECG signal dataset. Set
M Total number of clinical variables. Integer
di,j j-th feature of the i-th patient. Scalar
Darray Structured matrix representation of clinical data. Matrix
si ECG signal of patient i. Vector
ϕ(si) Feature extraction function applied to si. Function
fi Extracted feature vector of patient i. Vector
μf, σf Mean and standard deviation of features. Scalars
Dtrain,Dtest Training and testing subsets. Sets
Dprocessed Final preprocessed dataset. Set

Feature extraction

Following preprocessing, a comprehensive set of clinically relevant features was extracted from the ECG signals as demonstrated in Algorithm 2. These features, summarized in Table 3 and Algorithm 3 symbols, are described in Table 5, and were chosen as they are known to have physiological importance, and they can be used as powerful predictive biomarkers of treatment outcomes. The parameters that are extracted can give a quantitative insight into the electrophysiological characteristics of the heart.

  • Random Forest (Baseline): The first analysis starting with the Random Forest model was using the model to predict the characteristics with the strongest predictive power, whereby the QRS duration and PR interval were followed by the T wave amplitude.

  • XGBoost Model: The XGBoost model produced a different feature hierarchy. Although the QRS duration was the most important feature considered, the PR interval and the T-wave amplitude were not considered as crucial as the former. Rather, XGBoost placed more importance on the features that were connected to ventricular repolarization, including JTPEAK interval, T-wave symmetry, and T-wave flatness. This implies that the XGBoost model is better in identifying subtle morphological trends in the ECG data, especially in relation to the T-wave.

  • Random Forest (Optimized): After hyperparameter tuning using Grid Search, the feature importance within the Random Forest model shifted. However, although the QRS duration and PR interval were also meaningful, the T-wave symmetry and T-wave flatness became much more apparent, and they are more likely to be consistent with the XGBoost model results.

Table 3.

Symbol definitions for Algorithm 2 (ECG feature extraction)

Symbol Description Type/Dim.
si ECG signal of patient i. Vector
R Detected R-peaks in the ECG signal. Set
ϕ(si) Feature extraction function applied to si. Function
fi Feature vector of patient i. Vector
RR, PR, QT, QRS Interval-based ECG features. Scalars
JTPEAK, TPEAKTEND Advanced interval ECG features. Scalars
T-wave metrics Amplitude, asymmetry and flatness descriptors. Scalars
HRV features MeanNN, SDNN, RMSSD, pNN50. Scalars
F Feature matrix of all patients. Matrix

Table 5.

Symbol definitions for Algorithm 3 (model development and optimization)

Symbol Description Type/Dim.
D Preprocessed ECG dataset. Set
xi Feature vector of patient i. Vector
yi Treatment outcome label for patient i. Scalar
N Total number of samples. Integer
Franked Features ranked by Mutual Information. Set
τ Threshold for cumulative MI. Scalar
Fselected Selected feature subset. Set
MRF Optimized Random Forest model. Model
MSV M Optimized Support Vector Machine model. Model
MXGB Optimized XGBoost model. Model
P Predictions from base models. Vector
MStacked Final stacked ensemble model. Model
σ Sigmoid activation function. Function
W, b Weights and bias of logistic regression meta-classifier. Scalars

A combination of these models offered a feature set that gave more importance to the QRS complex and PR interval, which directly depend on the heart conduction times. In addition, the characteristics of Twave were regarded as significant in order to reflect the ventricular repolarization. This multi-model strategy highlighted the most relevant and helpful predictive feature in improving the final classification accuracy of the resulting models.

Algorithm 1

Data Preprocessing

Input: Raw clinical dataset D={di}i=1N, Raw ECG signals S={si}i=1N

Output: Preprocessed dataset Dprocessed

1: Step 1: Clinical Data Structuring

2: Represent clinical dataset D as a structured array:

Darray=d1,1d1,2⋯d1,Md2,1d2,2⋯d2,M⋮⋮⋱⋮dN,1dN,2⋯dN,M

 where di,j represents the j-th feature of the i-th patient.

3: Step 2: Feature Extraction from ECG Signals

4: for each signal si∈S and corresponding clinical data di∈Darray

5:   Extract key features ϕ(si) from the ECG signal:              

fi=ϕ(si)={fi,1,fi,2,…,fi,K}

 where fi,k represents the k-th extracted feature.

6:   Form feature-clinical pairs:                 

Fi={fi,di}

end for

8: Step 3: Dataset Splitting

9: Divide the extracted features and clinical data into training and testing subsets:          

Dtrain={fi,di}i=10.8N,Dtest={fi,di}i=0.8N+1N

10: Step 4: Signal Normalization

11: Apply normalization to ECG features F in Dtrain to prevent data leakage:                      

f′=fi−μf_trainσf_train

 where μf_train and σf_train are the mean and standard deviation computed strictly from Dtrain. The derived parameters are then applied to normalize Dtest.

12: Output Preprocessed Data

13: returnDprocessed={Dtrain_normalized,Dtest_normalized}

Algorithm 2

ECG Feature Extraction

Input: Preprocessed ECG signals S={si}i=1N

Output: Feature matrix F={fi}i=1N

 1: Step 1: For each ECG signal si∈S

   1. Detect R-peaks and fiducial points (P, Q, R, S, T).

   2. Compute temporal and interval features:

     •RR Interval (beat-to-beat variability)

     •PR Interval

     •QT Interval

     •QRS Duration

     •JTPEAK Interval

     •TPEAKTEND Interval

   3. Compute morphological T-wave features:

     •T-wave Amplitude

     •T-wave Asymmetry

     •T-wave Flatness

   4. Derive HRV (Heart Rate Variability) metrics:

     •MeanNN (mean RR interval)

     •SDNN (standard deviation of NN intervals)

     •RMSSD (root mean square of successive differences)

     •pNN50 (percentage of RR intervals > 50 ms)

   5. Create feature vector:

 2: Step 2: Construct feature matrix                 

F={f1,f2,…,fN}

 3: Step 3: Return F

List of top Features Across All Models: QRS Duration, PR Interval, Twave Amplitude, JPEAK, T-wave Flatness, Twave Asymmetry, HRV_MeanNN, RR Interval

These findings demonstrate how important it is to choose features that depict when and how the heart is working, which helps in a deep understanding of ECG signals, as in Table 4.

Table 4.

Physical parameters and obtained features from ECG signals with corresponding formulas

Parameter Description Formula
HRV21 Heart rate variability in beat-to-beat intervals, indexing neurocardiac function. N/A
RR Interval22 Time between consecutive R-peaks is used to assess autonomic control. RR=60HR(bpm)
PR Interval23 Time from atrial depolarization to ventricular depolarization. PR = t(Q) − t(P)
QT Interval24 Time from ventricular depolarization to repolarization. QT = t(T) − t(Q)
QRS Duration25 Duration of ventricular activation. QRS = t(S) − t(Q)
JT Peak Time from J-point to T-wave peak. JTpeak = Tpeak − J
TPEAKTEND Interval from the T-wave peak to its end. Tend − Tpeak
T-Wave Amp 26 T-wave peak magnitude relative to the isoelectric line. ∣Tpeak − Baseline∣
T-Wave Shape Captures asymmetry and flatness of the T-wave. N/A

Model Development To predict how well a treatment will work based on ECG features, this study discusses three machine learning models, i.e., Random Forest, XGBoost, and Support Vector Machine(SVM).

Algorithm 3

Model Development and Optimization Process

Input: Preprocessed ECG dataset D={xi,yi}i=1N

Output: Stacked ensemble model for treatment outcome prediction

1: Step 1: Feature Engineering and Selection

2: Perform feature importance analysis using Mutual Information (MI):

           Franked=RankFeaturesbyMI(x,y)

3: Select top k features based on cumulative MI threshold τ:

           Fselected←{xj:MIj>τ,j∈[1,k]}

4: Step 2: Model-Specific Training and Optimization

5: Random Forest:

6: Initialize with default parameters and define a hyperparameter grid:

7:           

param_grid=n_estimators∈{50,100,200},max_depth∈{None,10,20,30},min_samples_split∈{2,5,10}

8: Perform randomized grid search with stratified k-fold cross-validation.

9: Save the optimized model as MRF.

10: SVM:

11: Apply Radial Basis Function (RBF) kernel for non-linear classification:           

Φ(x)=exp−γ∣∣xi−xj∣∣2

12: Perform hyperparameter tuning on {C, γ}:           

paramgrid={C:[0.1,1,10],γ:[0.01,0.1,1]}

13: Save the optimized model as MSV M.

14: XGBoost:

15: Define hyperparameter grid:

16:

            param_grid = {

             learning_rate ∈ {00.01, 0.1, 0.2}

             n_estimators ∈ {50, 100, 200},

             max_depth ∈ {None, 3, 5, 7},

            }

17: Apply early stopping based on validation loss.

18: Save the optimized model as MXGB.

19: Step 3: Stacking Ensemble Learning

20: Combine predictions of base models using a meta-classifier:           

P={MRF(x),MSV M(x),MXGB(x)}

21: Train a Logistic Regression model on P to form the stacked ensemble:             

MStacked(x)=σW⋅P+b

22: Step 4: Model Evaluation

23: Evaluate MStacked using metrics:           

Metrics:Accuracy,Precision,Recall,F1−score

24: Compare against base models to validate improvement.

25: Output: Return MStacked and performance metrics.

strengths in classification tasks. The process of model development is shown in Algorithm 3 along with the symbol definitions in Table 5.

Evaluation Matrices Several evaluation indicators were employed in this study to gain a thorough understanding and assess each model’s performance. These metrics provided detailed information about the model’s ability to correctly categorize ECG data and predict treatment plans. Evaluation metrics were accuracy, precision, recall, F1-score, and confusion matrix analysis.

Hyper Parameter Tuning A grid search was used to adjust the Random Forest model’s hyperparameters in order to improve the model’s performance18. The following Algorithm 4 is used to modify hyperparameters using GridSearchCV. Table 6 explains all the symbols used in the mentioned algorithm 4.

Table 6.

Symbol definitions for Algorithm 4 (grid search for hyperparameter optimization)

Symbol Description Type/Dim.
D Dataset used for training and validation. Set
H Hyperparameter grid for Random Forest. Set
k Number of folds for cross-validation. Integer
Di i-th fold of the dataset used as the validation set. Subset
fh Random Forest trained with hyperparameters h. Model
acci Accuracy on the i-th validation fold. Scalar
acc¯h Average cross-validation accuracy. Scalar
best_accuracy Best accuracy observed across all combinations. Scalar
H* Optimal hyperparameter configuration. Set

Mathematical notation

Let D denote the input dataset, H be the hyperparameter grid, and h be a specific combination of hyperparameters. The number of folds for cross-validation is represented by k. For a given fold i, Di is the validation set. A Random Forest model with hyperparameters h is denoted by fh, and its accuracy on the validation set for fold i is acci. The average accuracy across all folds for a given hyperparameter set h is acc¯h, and the optimal set of hyperparameters is denoted by H*.

Algorithm 4

Grid Search for Hyperparameter Optimization in Random Forest

Require: Dataset D, Hyperparameter grid H, Number of folds k

Ensure: Optimal hyperparameters H*

 1: Initialize best_accuracy ← 0

 2: Initialize H*←∅

 3 for All combinations h∈H

 4:   Initialize sum_acc ← 0

 5:   for i = 1 to k do

 6:     Split D into training set Dtrain and validation set Dval

 7:     Train Random Forest model fh on Dtrain using hyperparameters h

 8:     Evaluate fh on Dval and get accuracy acci

 9:     sum_acc ← sum_acc + acci

10:   end for

11:  acc¯h←sum_acc/k

12:   if acc¯h>best_accuracythen

13:    best_accuracy←acc¯h

14:    H*←h

15:   end If

16: end for

17: return H*

Results

The models used in this study, such as Random Forest, XGBoost, and Support Vector Machine (SVM), showed impressive results in identifying the order of drug doses with the help of ECG-derived parameters and other clinical features. This section highlights the main findings, including the models’ accuracy, precision, recall, F1-scores, feature importance, and an analysis of the confusion matrix.

Model performance

Among the three models, XGBoost demonstrated the highest overall accuracy at 98.12%, followed by the Best Random Forest model with an accuracy of 97.63% and a mean accuracy of 96.97%. The accuracy of the SVM model was 45.90%. These results imply that while all models performed admirably in categorizing ECG signals, XGBoost outperformed the Best Random Forest by a small margin.

All models showed remarkable precision, recall, and F1-score outcomes. In particular, the weighted average F1-score of XGBoost was 0.98, that of Best Random Forest was 0.97, and that of SVM was 0.75. All models demonstrated high overall classification performance and the capacity to maintain a decent balance between precision and recall across different classes, as evidenced by the stable macro averages for precision, recall, and F1-score.

Table 7 compares the classification performance of all three models. XGBoost achieved perfect precision, recall, and F1-scores (1.00) for Class 0, while the other classes also maintained scores above 0.95.

Table 7.

Classification report across the ten treatment regimens

Class Precision Recall F1-Score Support
0 1.00 1.00 1.00 85
1 0.93 0.96 0.94 52
2 0.96 0.97 0.97 74
3 0.98 0.94 0.96 87
4 0.99 0.98 0.99 112
5 0.98 0.94 0.96 48
6 0.99 0.99 0.99 116
7 0.95 0.99 0.97 81
8 0.98 0.96 0.97 93
9 0.98 1.00 0.99 95

Feature importance analysis

Feature importance analysis was carried out for both Random Forest and XGBoost models to identify those ECG features that played the most significant role in the model’s predictions. The feature importance rankings from each model are illustrated in Fig. 3. It was revealed in the analysis that the QRS duration, T-wave amplitude, and PR interval consistently ranked as the most important predictors of treatment regimens in both of the models.

Fig. 3. Feature importance heatmap showing rankings across multiple models.

Fig. 3

The comparative visualization demonstrates the high predictive weight of specific physiological intervals, such as QT and QRS, across the evaluated classical ensemble pipelines.

In the Random Forest model, the QRS duration and PR interval emerged as the top features, contributing approximately 16% each to the predictions, respectively. Similarly, in the XGBoost model, these features demonstrated prominence of 16% and 13%, confirming their clinical relevance in reflecting the influence of treatment regimens on cardiac functions Figure 3 shows the comparative feature importance analysis across both models and in Table 7.

These results demonstrate the effectiveness of Random Forest,XGBoost, and SVM models for determining drug responses on cardiac signals. The high accuracy, precision, recall, and F1-scores, along with insightful feature importance analysis and confusion matrices, underscore the models’ potential for clinical application, optimizing treatment strategies based on ECG data.

Confusion matrix analysis

To ensure high-fidelity visualization, all classification accuracy charts and confusion matrices have been standardized to a unified, high-resolution format, accompanying a high-quality 12-lead ECG example (utilized for feature extraction). The standardized confusion matrices for each model given in Fig. 4 offer a detailed breakdown of their classification performance across the ten treatment regimens(Fig. 5).The matrices show the number of correct predictions (diagonal elements) versus misclassifications (off-diagonal elements) for each class. For the Random Forest model, the majority of predictions fell on the diagonal, indicating high accuracy in classification. Similarly, XGBoost exhibited minimal misclassifications, and SVM showed slightly more misclassifications, particularly between Class B-C-E-D-A and Class E-A-B-D-C, likely due to overlapping ECG features. The confusion matrix of the best-performing model, XGBoost, clearly indicates that most misclassifications involved classes with similar ECG characteristics. However, these misclassifications were rare, and the overall performance across all models demonstrated robust classification of ECG signals.

Fig. 4. Confusion matrices of different models.

Fig. 4

a Random Forest, b SVM, c XGBoost, d Best Random Forest. The matrices provide a detailed per-class breakdown of predictive accuracy and misclassification rates across the ten treatment groups.

Fig. 5.

Fig. 5

High-resolution 12-lead ECG sample illustrating the distinct spatial vectors utilized by the proposed feature extraction methodology.

The number of accurate predictions for each class (true positives) was indicated by diagonal elements, whereas the off-diagonal elements illustrate the instances of misclassification. For instance, the Random Forest model predicted Class A-D-E-C-B and Class E-B-A-C-D accurately 85 times and 95 times, respectively. However, there were minor misclassifications in other classes. These findings highlight the effectiveness of machine learning models such as Random Forest, XGBoost, and SVM in classifying ECG signals. The impressive accuracy, precision, recall, and F1-scores, combined with valuable feature importance analysis and confusion matrices, emphasize the potential of these models for clinical use in enhancing treatment strategies informed by ECG data.

External generalizability validation

To prove the robustness and generalizability of the findings, the machine learning pipeline was independently tested against an external dataset: PhysioNet’s ECGRDVQ (ECG Effects of Ranolazine, Dofetilide, Verapamil, and Quinidine). We streamed the raw .dat time-series data and corresponding clinical information through the identical preprocessing and feature extraction methodologies. The models achieved similarly high precision, recall, and F1 scores natively without retraining. These external validation results firmly establish the stability of the proposed approach on diverse patient populations.

Discussion

This study reveals that the ensemble methods are the best fit for this type of task, and overall underlines the significance of using machine learning for this problem. The Random Forest, being the accurate model with an accuracy of about 97.63%, proves that the computational methods are good at understanding complex, non-linear relationships between ECG occupied features and specific drug effects19.

In addition to overall accuracy, the models also demonstrate considerable results in other evaluation class metrics such as precision, recall, and F1-score. This depicts that the models are reliable and can clearly distinguish treatment groups, even if their effects on ECG are minor.

Crucially, the model’s internal logic aligns with established clinical knowledge. The feature importance analysis consistently ranked the QT interval and T-wave amplitude as the most influential predictors for classification. These features are well-understood clinical markers of cardiac repolarization, a process known to be highly sensitive to pharmacological intervention20. The fact that these models independently converged on these clinically validated features not only reinforces the physiological basis offindings of this study but also builds significant trust in the models’ decision-making processes.

This research achieves competitive results compared to earlier studies that used machine learning for ECG classification. Previous research mainly focused on identifying specific heart conditions, such as arrhythmias or ischemic events, using models like Support Vector Machines (SVMs), Neural Networks, or Convolutional Neural Networks (CNNs). Although these models have achieved high accuracy, they would frequently lack interpretability, which is essential for clinical use12. In this study, the Random Forest and XGBoost models not only achieved similar accuracy levels but also highlighted the key ECG features that significantly impact treatment outcomes. This finding addresses a gap in earlier research and illustrates how these models can enable more personalized and precise treatment strategies using ECG data.

Many previous studies did not concentrate on classifying ECG signals according to treatment regimens. This research shows that machine learning models can successfully distinguish between different drug effects, thus filling the previous void and laying the groundwork for enhancing treatment protocols in the future.

The outcomes of this study demonstrate the potential to use it in medical settings. By correctly identifying the right treatment sequences and more tailored options, we can improve personalized healthcare. For instance, if some patients are sensitive towards a particular medicine that increases the QT interval, the model can help find these patients early on. This will allow doctors to modify treatment plans before, and this will result in lower chances of adverse effects. Moreover, the big advantage is that these models are easily understandable, which is very crucial for medical settings. Highlighting the parts that are most important to predict how well the treatment will work will help medical professionals make better decisions, leading to better outcomes for patients. Adding machine learning models like these into daily medical work will make monitoring of patients more efficient and effective, especially in cases of need for quick results.

Considering the identified limitations and the encouraging results achieved, a few future research directions are proposed. First, there is a need to broaden the dataset to inculcate a more varied patient population to confirm the models’ effectiveness across different demographics and validate their generalizability. This can involve gathering ECG data of patients from diverse age groups, comorbidities, and treatment histories. Second, investigating alternative machine learning models, such as gradient boosting machines or deep learning techniques, could provide comparative insights into their performance against the Random Forest and XGBoost models. Third, the development of a system that will help doctors to use these models in their daily clinical practices, which will enable them to analyze the ECG results as soon as they are obtained, allowing for faster results. Finally, keeping track of patients over a long time can demonstrate how well the model predictions are working, which will make them more useful in future operations.

The research carried out shows how different machine learning methods, such as SVM, Random Forest and XGBoost, can be used to classify ECG signals and detect therapy responses. The Random Forest model achieved an astonishing 97.63% accuracy rate, while the accuracy rate of XGBoost is better than that, i.e., 98.12%. Both models demonstrate the satisfying results in distinguishing the effects of drugs on cardiac electrical activity, illustrated by their high precision, recall and F1-score across various categories.

As seen in the analysis of important features, the QT interval and T-wave amplitude are the most dominant in predicting the treatment results. These features are proven important in cases of questions about heart recovery and the reactions of drugs on the body. With an approval to model’s predictions, the outputs also provide new insights into physical signs and treatment outcomes.

Although the results are promising, It persists some limitations. The primary one is the lack of diversity in our dataset, along with the need for more testing across a wider range of patients to validate the results of this study.

Notwithstanding these difficulties, this study advances the field of AI-assisted healthcare by applying machine learning-based techniques to increase the accuracy and effectiveness of ECG analysis, especially when it comes to categorizing medication regimens.

In conclusion, this study lays a strong foundation for applying machine learning in ECG-based treatment classification, paving the way for more personalized and data-driven approaches in clinical practice.

Acknowledgements

The authors declare that no specific funding was received for this work.

Author contributions

Vibha Tiwari: conceptualization, supervision, investigation, advisory role—contributed to the initial brainstorming of research ideas, provided technical feedback during early stages and guided the team through intermediate phases of experimentation, writing, review and editing. Rohit Gupta: conceptualization, methodology, data curation, software, validation, formal analysis, visualization, investigation, writing—original draft preparation. Akshada Telang: writing, review, and editing, organization of manuscript sections, assistance in drafting the introduction and related work, guidance on structure and clarity of the paper. Akshara Tiwari: project support, coordination, provided assistance to the team in ensuring the successful completion of the research, contributed to organizing experiments and documentation, and supported the overall workflow during model implementation and paper drafting. Rebakah Geddam: writing, review and editing, visualization, supervision, assisted in final manuscript evaluation, formatting, and refinement, contributed to drafting multiple sections, and provided direction on technical presentation and writing standards. Muhammad Awais: conceptualization, supervision, methodology, offered continuous advisory support, contributed to the exploration of research directions, provided guidance on coding challenges, and advised on methodological and analytical improvements. Muhammad Ahmed Khan: continuous advisory support, contributed to exploration of research directions, provided guidance on coding challenges, and advised on methodological and analytical improvements. Hemant Ghayvat: conceptualization, supervision, methodology, offered continuous advisory support, contributed to the exploration of research directions, provided guidance on coding challenges, and advised on methodological and analytical improvements.

Funding

Open access funding provided by Linnaeus University.

Data availability

The datasets used and/or analyzed during the current study are available in the following public PhysioNet repositories: ECG Effects of Dofetilide, Moxifloxacin, Dofetilide+Mexiletine, Dofetilide+Lidocaine and Moxifloxacin+Diltiazem(ECGDMMLD) database: https://physionet.org/content/ecgdmmld/1.0.0/—ECG Effects of Ranolazine, Dofetilide, Verapamil, and Quinidine (ECGRDVQ) database: https://physionet.org/content/ecgrdvq/1.0.0/. Additional processed data generated during the study are available from the corresponding author upon reasonable request.

Code availability

The code used for data preprocessing, feature extraction, and model development is available at:https://github.com/Guptarohit2003/ECG-Treatment-Classification.

Competing interests

The authors declare no competing interests.

Footnotes

Publisher’s note Springer Nature remains neutral with regard to jurisdictional claims in published maps and institutional affiliations.

References

  • 1.de Roos, A. & Nikolaou, K. in CT and MRI in Suspected Ischemic Heart Disease. 179–187 (Springer International Publishing, Cham, 2019). [PubMed]
  • 2.Ashley, E. A. & Niebauer, J. Cardiology Explained London: Remedica; Chapter 3, Conquering the ECG. Available from: https://www.ncbi.nlm.nih.gov/books/NBK2214/ (2004). [PubMed]
  • 3.Johannesen, L. et al. Improving the assessment of heart toxicity for all new drugs through translational regulatory science. Clin. Pharmacol. Therapeut.95, 501–508 (2014). [DOI] [PubMed] [Google Scholar]
  • 4.Lyon, A., Mincholé, A., Martínez, J. P., Laguna, P. & Rodriguez, B. Computational techniques for ECG analysis and interpretation in light of their contribution to medical advances. J. R. Soc. Interface15, 20170821 (2018). [DOI] [PMC free article] [PubMed] [Google Scholar]
  • 5.Adasuriya, G. & Haldar, S. Next generation ECG: The impact of artificial intelligence and machine learning. Curr. Cardiovasc. Risk Rep.17, 1–12 (2023).36465151 [Google Scholar]
  • 6.Attia, Z. I. & Friedman, P. A. Explainable AI for ECG-based prediction of cardiac resynchronization therapy outcomes: learning from machine learning?. Eur. Heart J.44, 693–695 (2022). [DOI] [PubMed] [Google Scholar]
  • 7.Johannesen, L. et al. Late sodium current block for drug-induced long QT syndrome: Results from a prospective clinical trial. Clin. Pharmacol. Therapeut.99, 214–223 (2016). [DOI] [PMC free article] [PubMed] [Google Scholar]
  • 8.Rafie, N., Kashou, A. H. & Noseworthy, P. A. Ecg interpretation: clinical relevance, challenges, and advances. Hearts2, 505–513 (2021). [Google Scholar]
  • 9.In Chou’s Electrocardiography in Clinical Practice (Sixth Edition) (eds. Surawicz, B. & Knilans,T.K.) (W.B. Saunders, Philadelphia, 2008). 10.1016/B978-141603774-3.50001-X.
  • 10.Ren, H., Jin, H., Chen, C., Ghayvat, H. & Chen, W. A novel cardiac auscultation monitoring system based on wireless sensing for healthcare. IEEE J. Transl. Eng. Health Med.6, 1–12 (2018). [DOI] [PMC free article] [PubMed] [Google Scholar]
  • 11.Osowski, S., Siwek, K. & Markiewicz, T. MLP and SVM networks a comparative study. 46, 37– 40 10.1109/NORSIG.2004.250120 (2004).
  • 12.Acharya, U. R. et al. A deep convolutional neural network model to classify heartbeats. Comput. Biol. Med.89, 389–396 (2017). [DOI] [PubMed] [Google Scholar]
  • 13.Kiranyaz, S., Ince, T. & Gabbouj, M. Real-time patient-specific ECG classification by 1D convolutional neural networks. In IEEE Transactions on Bio-Medical Engineering. Vol. 63 (IEEE, 2015). [DOI] [PubMed]
  • 14.Tiwari, V. et al. An efficient sparse code shrinkage technique for ECG denoising using empirical mode decomposition. Technol. Health Care33, 1773–1786 (2025). [DOI] [PubMed]
  • 15.Asadi, S., Roshan, S. & Kattan, M. W. Random forest swarm optimization-based for heart diseases diagnosis. J. Biomed. Inform.115, 103690 (2021). [DOI] [PubMed] [Google Scholar]
  • 16.Pokkuluri, K. S. et al. Bridging the gap between technology and medicine through the revolutionary impact of the healthcare Internet of Things on remote patient monitoring. J. Intell. Syst. Internet Things2, 212–212 (2024). [Google Scholar]
  • 17.Tiwari, V., Ganga, G., Singhai, J. & Azad, M. Wavelet based noise robust features for speaker recognition. Signal. Process. Int. J.5, 52–64 (2011). [Google Scholar]
  • 18.Pedregosa, F. et al. Scikit-learn: Machine learning in Python. J. Mach. Learn. Res.12, 2825–2830 (2011). [Google Scholar]
  • 19.Breiman, L. Random forests. Mach. Learn.45, 5–32 (2001). [Google Scholar]
  • 20.Kligfield, P. et al. Recommendations for the standardization and interpretation of the electrocardiogram. Circulation115, 1306–1324 (2007). [DOI] [PubMed]
  • 21.Shaffer, F. & Ginsberg, J. P. An overview of heart rate variability metrics and norms. Front. Public Health5, 10.3389/fpubh.2017.00258 (2017). [DOI] [PMC free article] [PubMed]
  • 22.Byku, M. & Mann, D. in Cardioskeletal Myopathies in Children and Young Adults (eds. Efferies, J. L., Blaxall, B. C., Robbins, J. & Towbin, J. A.), 381–397 (Academic Press, Boston, 2017).
  • 23.Douedi S, D. H. P wave [updated 2023 Jul 24] (StatPearls Publishing, Treasure Island (FL), 2024).
  • 24.Schiavone, M. Arrhythmogenic risk and mechanisms of QT-prolonging drugs to treat COVID-19. Card. Electrophysiol. Clin.14, 95–104 (2022). [DOI] [PMC free article] [PubMed] [Google Scholar]
  • 25.In Chou’s Electrocardiography in Clinical Practice (Sixth Edition) (eds Surawicz, B. & Knilans, T. K.) 1–28 (W.B. Saunders, Philadelphia, 2008). 10.1016/B978-141603774-3.10001-2.
  • 26.In Chapter 6 - Morphology of normal resting electrocardiogram (ed. Malik, M.) Sex and Cardiac Electrophysiology, 63–72 (Academic Press, 2020). 10.1016/B978-0-12-817728-0.00006-1.

Associated Data

This section collects any data citations, data availability statements, or supplementary materials included in this article.

Data Availability Statement

The datasets used and/or analyzed during the current study are available in the following public PhysioNet repositories: ECG Effects of Dofetilide, Moxifloxacin, Dofetilide+Mexiletine, Dofetilide+Lidocaine and Moxifloxacin+Diltiazem(ECGDMMLD) database: https://physionet.org/content/ecgdmmld/1.0.0/—ECG Effects of Ranolazine, Dofetilide, Verapamil, and Quinidine (ECGRDVQ) database: https://physionet.org/content/ecgrdvq/1.0.0/. Additional processed data generated during the study are available from the corresponding author upon reasonable request.

The code used for data preprocessing, feature extraction, and model development is available at:https://github.com/Guptarohit2003/ECG-Treatment-Classification.


Articles from NPJ Systems Biology and Applications are provided here courtesy of Nature Publishing Group

RESOURCES