Deep Neural Networks Generalization and Fine-Tuning for 12-lead ECG
  Classification
Numerous studies are aimed at diagnosing heart diseases based on 12-lead
electrocardiographic (ECG) records using deep learning methods. These studies
usually use specific datasets that differ in size and parameters, such as
patient metadata, number of doctors annotating ECGs, types of devices for ECG
recording, data preprocessing techniques, etc. It is well-known that
high-quality deep neural networks trained on one ECG dataset do not necessarily
perform well on another dataset or clinical settings. In this paper, we propose
a methodology to improve the quality of heart disease prediction regardless of
the dataset by training neural networks on a variety of datasets with further
fine-tuning for the specific dataset. To show its applicability, we train
different neural networks on a large private dataset TIS containing various ECG
records from multiple hospitals and on a relatively small public dataset
PTB-XL. We demonstrate that training the networks on a large dataset and
fine-tuning it on a small dataset from another source outperforms the networks
trained only on one small dataset. We also show how the ability of a deep
neural networks to generalize allows to improve classification quality of more
diseases.
Aram Avetisyan, Shahane Tigranyan, Ariana Asatryan, Olga Mashkova, Sergey Skorik, Vladislav Ananev, Yury Markin
# Deep Neural Networks Generalization and Fine-Tuning for 12-lead ECG Classification

###### Abstract

Numerous studies are aimed at diagnosing heart diseases based on 12-lead electrocardiographic (ECG) records using deep learning methods. These studies usually use specific datasets that differ in size and parameters, such as patient metadata, number of doctors annotating ECGs, types of devices for ECG recording, data preprocessing techniques, etc. It is well-known that high-quality deep neural networks trained on one ECG dataset do not necessarily perform well on another dataset or clinical settings. In this paper, we propose a methodology to improve the quality of heart disease prediction regardless of the dataset by training neural networks on a variety of datasets with further fine-tuning for the specific dataset. To show its applicability, we train different neural networks on a large private dataset TIS containing various ECG records from multiple hospitals and on a relatively small public dataset PTB-XL. We demonstrate that training the networks on a large dataset and fine-tuning it on a small dataset from another source outperforms the networks trained only on one small dataset. We also show how the ability of a deep neural networks to generalize allows to improve classification quality of more diseases.

 Electrocardiography, time series analysis, deep learning, ECG classification, fine-tuning, pre-trained neural networks

## I Introduction

cardiovascular diseases nowadays represent the leading cause of death. Several tests are commonly used to diagnose heart conditions. For instance, tests such as echocardiograms can more accurately determine the presence of disease than others. However, some of them are generally not easily accessible to patients, require specialized equipment, and are also time-consuming and expensive.

Electrocardiography (ECG) is a non-invasive tool to assess the general cardiac condition of a patient. Due to it being a fast, painless, efficient, and low-maintenance test, it is used as the primary method for diagnosing cardiovascular diseases. In this paper, we focus on the improvement of the most common type of ECG records used by medical institutions, short 12-lead ECGs.

Despite the wide application of ECG recording, ECG analysis is a complex task that requires the expertise of a specialist with broad specific knowledge. Often not only the health but also the life of the patient depends on the timely decoding of all the data. This is further complicated by the difficulty of manual ECG analysis, which increases the likelihood of errors or incompleteness of diagnosis in interpretation. Therefore, numerous studies aim to detect abnormalities using automated methods such as applying DNNs in ECG analysis.

Automated interpretation in ECG analysis can transform the ECG into a screening tool and predictor of diseases. However, despite the great development of various deep learning methods applied to ECGs, there are still significant limitations that do not allow us to assert the success of these methods in a clinical setting with more non-unified and noisy data.

The number of digital ECGs is increasing dramatically. There are promising studies that use classical machine learning methods to detect cardiac abnormalities [1, 2]. Nevertheless, the most popular methods for analyzing ECGs are DNNs. To detect an abnormality, the researchers either use raw or preprocessed ECG signals [3, 4] or convert signals to images using wavelet or short-time Fourier transform [5, 6, 7]. Multiple surveys describe deep learning methods for ECG classification [8, 9].

Most of the studies use partial and end-to-end deep learning techniques with convolutional layers and residual connections. Several approaches have already shown cardiologist-level performance for some cardiac abnormalities [10].

One of the main problems that arise in medical domain studies is the small amount of data. The data is often difficult to obtain because of privacy and security reasons. Consequently, few papers use large amounts of ECG data [11, 12]. Even with a large dataset available [11], there may be challenges because the diagnosis is usually presented in text form. In this case, labels have to be extracted from textual reports, which can lead to additional errors [13].

Most of the studies that analyze 12-lead ECGs use open datasets, such as PTB-XL, CPSC2018, Chapman-Shaoxing Database [14, 15, 16], for evaluation. These datasets consist of several thousand ECGs with fixed parameters such as duration and frequency. In addition, each dataset is preprocessed
and annotated by a small group of cardiologists, who can make similar mistakes during annotation. Due to the small number of samples in open datasets, neural networks are limited to the number of abnormalities that they can classify well. Thus, DNNs trained on these datasets to predict widespread abnormalities do not show the same quality on datasets from different domains.

Several studies demonstrate that the same DNNs trained on different datasets show significantly different results on their respective test datasets even for the most popular heart diseases such as atrial fibrillation [17, 18, 19]. Such a difference in prediction performance for various ECG datasets makes the networks less robust. This makes it impossible to widely use them on clinical datasets nowadays.

In this paper, we propose a methodology to improve the accuracy of ECG classification. We demonstrate that training DNN on a large dataset assembled from a variety of different datasets and then fine-tuning it on a relatively smaller dataset improves abnormality prediction for this specific dataset. Additionally, we demonstrate that DNNs trained on a large dataset have good generalization ability for ECG analysis and can help to improve prediction results for different datasets.

We conduct the experiments using a large, assembled dataset TIS of raw 12-lead ECG records and one of the most popular public datasets PTB-XL [14]. We compare DNNs with different architectures trained on TIS and PTB-XL for 7 selected abnormalities and show that neural networks trained on TIS show stable prediction quality regardless of the test data whereas networks trained on PTB-XL start degrading on the data from a different source. We also demonstrate, for two selected abnormalities, that trained DNNs deliver results comparable to cardiologists' one.

## 2 Methods

### Dataset retrieval and preprocessing

Two datasets are used for analysis. The first one is a publicly available PTB-XL dataset of 21,837 ECG records [14]. All ECGs in PTB-XL are 10 seconds in duration and have a 500 Hz frequency. The ECGs are preprocessed by a bandpass filter to reduce the noise and annotated by up to 2 cardiologists. The second one is the TIS dataset of more than 1,500,000 12-lead ECGs collected from multiple hospitals over 2 years with almost 57% of labeled records annotated by more than 130 cardiologists. The data is stored in signal format and does not have any initial preprocessing. These hospitals use different devices to record ECGs in a clinical setting. As a result, the dataset is heterogeneous in various parameters: types of recording devices, frequency, duration, etc. For this research, we use 549,279 records from the TIS dataset, which are collected and annotated by the doctors for the period from December 2019 to December 2021. Ethical approval was granted by the Ethics Committee of the I.M. Sechenov First Moscow State Medical University (Protocol No. 06-23).

One of the important advantages of records in TIS is the initial annotation of the dataset with labels apart from textual diagnoses. Existing research suggests methods to extract diseases from textual diagnoses [11, 20]. However, these methods perform with a certain percentage of errors, which can affect the prediction. TIS dataset is developed in a way that each doctor can select the abnormality from the list of heart diseases along with writing a diagnosis. Therefore, there is no need to use the algorithms to retrieve the labels from texts, potentially creating additional errors in the dataset.

To conduct valid experiments, TIS and PTB-XL formats should be standardized. Therefore, annotated TIS records are filtered and converted to the same data format as PTB-XL. For training and validation, we selected ECG records of 9-10 seconds duration and 500, 1000 Hz frequency. All records are resampled to 500 Hz and zero-padded to 10 seconds. For the TIS test dataset, we use only 10-second ECG records with 500 Hz frequency. We also considered only patients older than 18 years.

Errors can appear while recording ECGs in hospitals, for example, in case of a bad electrode cable connection or improperly working cardiographs. To avoid these errors, the records that had at least one lead with the constant value are removed during data preprocessing.

The output ECG signal characteristics can vary in datasets because they depend on the recording devices, the systems, and the formats in which they are stored. For example, PTB-XL and TIS records have 1.6 and 2906 average amplitude respectively, therefore, can be interpreted incorrectly by the DNNs without preprocessing. To achieve a similar average amplitude, we apply z-score normalization to both datasets after the initial transformations.

### Model architecture and training

We use a popular DenseNet model [21] from the family of CNNs widely used in ECG classification studies [22] which is adapted for unidimensional data. We also reviewed the DNNs proposed in [23]. To avoid adjusting architecture to a specific dataset, we use default values for the kernel size, convolutional layers number, and node number per layer for DenseNet. We use default parameters for the other observed DNNs for the same reasons.

The observed DenseNet model consists of a Convolutional (Conv) layer with kernel size 7, followed by a max pooling layer, 4 Dense blocks, and 3 Transition blocks. The output of the last Dense block is fed into the Adaptive Average Pooling layer and the fully connected layer for classification. The first Conv layer and each layer inside the Dense block are followed by batch normalization and ReLU activation function. For the Transition block, we use average pooling with kernel size 2. The architecture of DenseNet is presented in Fig. 1.

We split both TIS and PTB-XL datasets into train and test parts and use the test dataset to evaluate the DNNs. The test datasets are fixed for the experiments and the models trained on TIS and PTB-XL are both evaluated on the same data. After filtering, preprocessing, and splitting the data 549,279 ECG records from the TIS dataset are selected for training and validation, and 31,872 records are used to evaluate the DNNs. The characteristics of TIS are presented in Table 1. ECGs recorded during two selected months are used from the TIS dataset for tests. PTB-XL has a parameter in a database
parameter to divide the dataset for training and testing. Hence, ECG records of the 10th fold are selected for the test dataset, other records are used for training and validation.

For each selected abnormality, we trained a binary classifier. Each trained neural network has the same input format of the ECG records of 10 seconds duration with a 500 Hz frequency. We use binary cross-entropy with logit loss which is minimized with the Adam optimizer [24]. The optimizer has default parameters with a learning rate of 0.003. Due to class imbalance, we use weighted loss, giving higher weight to the positive class based on the proportion of presence. The learning rate is reduced by a factor of 0.8 whenever the validation loss does not present any improvement for 3 epochs in a row. The convolutional layers' weights are initialized with Kaiming normal values [25]. The rest of the layers are initialized with constant weight and zero bias. The training runs for 100 epochs with an early stopping with the patience of 20. Finally, the DNN with the best validation loss during training is selected.

### Hyperparameter tuning

We use stratified cross-validation with 5 folds to find the best values for hyperparameters for both datasets. We repeated the selection, training, and evaluation process 15 times. To select optimal values for learning rate and reducing factor, we use the following options: learning rate in the range of 0.001 to 0.003 and factor between 0.4 to 0.8. The best metrics are achieved for the learning rate equal to 0.003 and the factor to 0.8. On the one hand, such a choice is enough to ensure convergence with little steps, on the other hand, it is small enough to avoid divergent behavior. Activation function ReLU is chosen among ReLU, ELU, SELU, and LeakyReLU. For the batch size, we selected 256, the maximum value that can fit in the memory of the GPU.

We want to demonstrate how pre-training the DNN on the variety of datasets combined into one affects the prediction results on the other dataset. We train the models on the TIS dataset and use obtained weights to fine-tune them on the PTB-XL dataset. We selected the same architecture to train the neural network and froze the first blocks of the pre-trained DNN. Then the weights of the last layers are randomly initialized and fine-tuned on PTB-XL. We set multiple experiments to find the best size for the number of blocks of DenseNet to freeze as well as the learning rate. The parameters are chosen from the following options: for the number of frozen blocks 5, 7, 9, for learning rate 0.001, 0.002, 0.003. The best metrics on the PTB-XL test dataset are achieved when 7 blocks of DenseNet are frozen and the learning rate is equal to 0.003.

Figure 1: The DenseNet architecture for ECG classification.

Figure 2: Scheme of experiments to compare TIS_dn, PTBXL_dn, and TIS_tuned_dn.
## 3 Experiments and Results

We set up experiments to compare the effect of the training datasets on ECG classification. We use both test datasets to evaluate neural networks for each selected abnormality trained exclusively on the observed dataset. Furthermore, we use PTBXL test data to investigate the effect of pre-training the DNN on the large dataset.

We compare three neural networks with the same architectures: the network pre-trained on TIS and fine-tuned on PTBXL (TIS_tuned_dn), and the ones trained either on PTB-XL (PTBXL_dn) or TIS (TIS_dn). The scheme of the performed experiments is shown in Fig. 2.

We selected 7 abnormalities according to SCP-ECG standards to train the DNNs: Atrial FIBrillation (AFIB), Right Bundle Branch Block (RBBB), Sinus TACHycardia (STACH), Sinus BRADycardia (SBRAD), first-degree AV Block (1AVB), Left Bundle Branch Block (LBBB), and Premature Ventricular Complexes (PVC). We should note that we merged Complete and Incomplete Left Bundle Branch Blocks (CLBBB and ILBBB) into one disease: the Left Bundle Branch Block (LBBB). Similarly, we merged Complete and Incomplete Right Bundle Branch Blocks into the Right Bundle Branch Block (RBBB). These abnormalities are common and widely represented in each of the considered datasets. The distribution of abnormalities for both datasets is summarized in Table 2.

The prediction results of the networks on TIS and PTB-XL test datasets are presented in Table 3 and 4, respectively. We chose Sensitivity (Sens.), and Specificity (Spec.) metrics to compare the quality of the DNNs. These are widely used metrics for ECG analysis [26] Sensitivity assesses how well the model finds people with heart diseases. Specificity gives an estimate of how accurately the model detects people without a disease. We also count G-mean and F2-score to understand which neural network performs better. Higher values of the considered metrics would indicate which model gives more accurate abnormality prediction.

Comparison of the DNNs demonstrates the importance of large and diverse train data. TIS_dn models generalize disease classification significantly better than PTBXL_dn models and are stable regardless of the test dataset. For most of the observed abnormalities, TIS_dn models show comparable quality on the PTB-XL test dataset to PTBXL_dn models. On the contrary, the metrics of the PTBXL_dn decrease on the TIS test dataset. Different training data have a smaller impact on prediction quality for abnormalities that have less variety among patients. Therefore, the metrics of the PTBXL_dn DNNs detecting atrial fibrillation or right bundle branch block demonstrate a moderate change. However, the difference becomes significant for other heart diseases such as IAVB, PVC, or LBBB and reaches up to 10% for G-mean.

TIS_tuned_dn networks give promising results. Considering the observed metrics, a TIS_tuned_dn gives better predictions as compared with both TIS_dn or PTBXL_dn networks for all the abnormalities. The G-mean metric is increased by up to 2% compared to TIS_dn and up to 4% compared to PTBXL_dn, which is a significant improvement in the quality of ECG classification. Moreover, if G-mean does not have a significant improvement, F2-score increases dramatically, which means that a TIS_tuned_dn can much better detect people with abnormalities.

We also trained several neural networks with different architectures apart from DenseNet. We conducted the same experiments with various neural networks used as benchmarks for the classification of the PTB-XL dataset [23] and achieved the same results. The results of the experiments for these DNNs are presented in Appendix Tables 6 - 6.

The TIS dataset is large, which affects the quality of classification and helps to generalize the DNNs. However, we demonstrate that there are other characteristics of each dataset apart from the size that influence the DNN prediction performance. We run the experiments halving the size of the TIS training dataset with the maintaining proportions of abnormality prevalence to show that fine-tuning on relatively small PTB-XL will still improve the classification of PTB-XL test data. We selected 2 abnormalities AFIB and PVC and trained the DenseNet model on a halved TIS train dataset (hTIS_dn). Then we froze the layers of pre-trained networks and fine-tuned them on PTB-XL (hTIS_tuned_dn), which is almost 30 times smaller than TIS.

The comparison of the DNNs trained on datasets of different sizes on PTB-XL test data is presented in Table 5. The metrics are not improved for the hTIS_dn model compared to PTBXL_dn and TIS_dn. Wherein, the metrics of hTIS_tuned_dn models are the best among the observed neural
networks. Despite halving the training dataset and reducing the number of samples by almost 300,000, fine-tuning the model with approximately 17,000 samples from another data source improves the metrics on PTB-XL. We demonstrate that a model trained on a much smaller but specific dataset showed higher quality on the selected test data compared to the models trained on the full-size dataset.

To estimate the quality of DNNs in clinical practice, we compared their prediction with the independent ECG evaluation by three doctors from different hospitals with years of experience in reading and diagnosing ECG records. We took a random subset of 500 samples from the PTB-XL test dataset with the maintaining proportions of the classes. Each cardiologist annotated these 500 records selecting whether two abnormalities observed in this paper (AFIB and PVC) are present in the ECG record. The subset of PTB-XL had 34 and 26 ECG records with AFIB and PVC respectively. After the evaluation, we compared the annotation of the doctors with the PTBXL_dn and TIS_tuned_dn DNNs.

The prediction performance of Densenet networks and the doctors' annotation on a subset of 500 ECGs are presented in Table VI. We also plot sensitivity/specificity curves in Fig. 3 and confusion matrices of the doctor's annotation and the DNNs prediction in Appendix Fig. 4, 5. The metrics demonstrate that TIS_tuned_dn outperforms 2 cardiologists for AFIB and all the cardiologists for PVC.

## IV Discussion

Despite many convincing studies on 12-lead ECG classification, the research rarely addresses the problem of generalization of the neural networks. This is primarily since usually there is no opportunity to train the DNNs on large amounts of data from various sources. Most studies use the same train and test dataset for the ECG analysis [26], and there are a few researchers that use different datasets [27, 28]. However, they are trained and validated on the same dataset. This eliminates the possibility of correctly validating the DNNs on ECGs from various sources because records may differ for multiple
reasons. For instance, data can be initially preprocessed during the ECG recording or later during the doctors' annotation. Another possible reason that can cause the difference in the quality of records is the diversity of ECG devices that can record ECGs with specific parameters, filtering, or distinct noise.

Large and heterogeneous ECG data help with networks' generalization. We demonstrate that DNNs trained on the collection of different datasets maintain high metrics for different datasets for the observed heart diseases and show metrics comparable to clinical quality on data from another domain for two selected abnormalities. DNNs trained on open datasets can achieve good initial results for several cardiac abnormalities, but they are unstable for data from different domains. It is necessary to use training data from different sources to be able to generalize the neural network. Another attempt to make the network more stable is to create a unified approach to filtering and preprocessing during data collection. Most of the open data is initially preprocessed, which may affect the loss of features that determine the abnormality of the record. One of the ways to solve this problem can be publishing raw ECG signals in addition to preprocessed data.

An important observation from the experiments in this paper is that neural networks trained on many various data can improve in quality with a relatively small increase in the training data. These results allow us to fine-tune the DNNs on datasets from different sources to get better prediction performance. Thus, researchers who do not have large amounts of data can achieve high-quality results on relatively small amounts of data.

The good prediction performance of the DNNs trained to diagnose 12-lead ECGs does not limit the potential for improvement. As the next steps to develop existing classification methods, new parameters, which can lead to the better generalization of the neural networks, must be considered. First of all, these are patient metadata, which will give additional information for certain records. There are already some developments in analyzing metadata [29], however, the analysis has limitations. The reason for that is a small amount of additional information about a record due to security reasons or the lack of a single system for storing patients' data. One of the solutions to the problem associated with the confidentiality of storing patients' metadata can be an identification of a person by the ECG [30].

To improve the abnormality prediction models, it will be helpful to develop algorithms for each disease individually. In some cases, there is no need to use the entire ECG record when only a few parts are sufficient. This approach can simplify the neural networks by not providing the parts of the record that are not affected by the considered abnormality. In addition, algorithms should be tested on a variety of real-time data from different sources with feedback from cardiologists. This

Figure 3: Sensitivity-specificity curves show the prediction quality for PTBXL_dn and TIS_tuned_dn networks to detect atrial fibrillation (AFIB) and premature ventricular complexes (PVC). Points correspond to the performance of three different doctors’ annotations.
will help in analyzing incorrectly predicted samples and early identification of the errors in the algorithm.

The ability to fine-tune the DNNs pre-trained on a large dataset allows us to work on the described improvements. Researchers can use the networks as backbones for more complex architectures to achieve the best quality. ECG metadata and hand-crafted features can be used with the DNNs to evaluate their influence on the prediction. The weights of the neural networks can also be used for transfer learning for studies that do not have a lot of labeled data, for instance, analysis of ECG records to detect hyperkalemia, hypokalemia [31], or human emotions [32]. Moreover, trained networks can be used as benchmarks for datasets from different sources and provide the possibility to verify new models.

## 5 Conclusion

Deep neural networks have achieved promising results in predicting heart diseases with ECG records. However, due to the difference in ECG records from multiple data sources and the small amount of available data for training, current DNNs are not generalized to be widely applied in practice.

In this paper, we present the methodology to achieve better abnormality prediction quality regardless of the dataset. We demonstrate that training neural networks on a variety of datasets with further fine-tuning on the specific dataset shows better quality than DNN trained on this specific data set only. This approach can help the application of DNNs for ECGs analysis in medical centers that have different data sources. In addition, it can reduce both the cost and time spent on data annotation by cardiologists, since this approach requires less labeled data.

We also show the significance of a large diverse data for a generalization of the neural networks. The improvement of generalization ability leads to the more efficient use of neural networks in real-life applications. We demonstrate that current DNNs trained on a large collection of different datasets and fine-tuned for the selected dataset can achieve cardiologist-level performance. The proposed methodology can be applied to new algorithms and architectures, thereby providing better prediction quality.

For further improvement, we consider the analysis of ECG metadata for abnormality classification. Considering additional information about the patient can be substantial and give more accurate predictions. Moreover, we consider only patients that are older than 18 years. This limitation has to be considered when implementing new methods for ECG classification due to criteria for diagnosing children's and adults' heart diseases may differ, which can cause the inability of trained DNNs to predict the abnormalities accurately. One of the approaches would be training different models for predicting cardiac abnormalities in children and adults.
