Dynamic electrocardiogram detection and diagnosis based on improved dilated convolutional network Authors: Hangli Wang, Yinghao Jia, Chunxiang Zhu, Zhijie Shen Published: 2026 ABSTRACT AbstractElectrocardiograms (ECGs) are crucial for promptly detecting heart disease, assessing cardiac function, and guiding treatment, making them a key clinical tool. However, traditional ECG monitoring systems are confronted with numerous challenges. This paper presents a dynamic ECG monitoring and diagnostic system that integrates the two major developmental directions of ECG monitoring systems, namely portability and intelligent diagnosis. The portable acquisition terminal is compact, measuring only 80 mm × 100 mm and weighing approximately 150 g, so patients can easily carry it. The terminal connects to the host computer via Wi-Fi, and the acquired data is wirelessly transmitted for subsequent processing. For arrhythmia classification, this paper proposes a network architecture model that combines hybrid dilated convolution with hybrid attention mechanisms. Our hybrid dilated convolution module reduces the number of network parameters, solving key problems with traditional dilated convolution. The hybrid attention module precisely captures global dependencies in spatial and channel dimensions, enhancing diagnostic accuracy. In practical testing, the system demonstrates excellent performance. The AD8232 chip, in conjunction with Hierarchical Kalman filtering, efficiently processes ECG signals and successfully suppresses noise interference. The system maintains high accuracy, with resting heart rate measurements staying within ±2% of the true value, and exercise heart rate within ±4%. The display interface of the host computer presents clear ECG waveforms and accurate classification results. The model achieves a per-beat overall classification accuracy of 99.28% under the AAMI EC57 five-class standard, with a macro-averaged F1-score of 96.45% and a macro-averaged MCC of 0.9561 across the four evaluable classes (N, S, V, F), indicating high stability and statistical reliability. Keywords: Electrocardiograms, Diagnosis, Portable, Hybrid dilated convolution, Hybrid attention mechanismsSubject terms: Cardiology, Computational biology and bioinformatics, Engineering, Health care, Mathematics and computing Introduction While modern technology has raised living standards, irregular lifestyles and unhealthy dietary habits have simultaneously become more prevalent, leading to a rise in various cardiovascular and cerebrovascular diseases. Due to their insidious onset and irregular occurrence, cardiovascular diseases have become the leading cause of morbidity and mortality both in China and worldwide. According to relevant data, deaths from cardiovascular diseases account for approximately one-third of global mortality, with more than 17 million individuals dying annually, which is equivalent to one death every ten seconds1,2. ECG is a technique that records the electrical activity of the heart throughout each cardiac cycle using an ECG machine3. Physicians can evaluate cardiac health by identifying pathological elevations or depressions in ECG waveform segments. At present, the diagnosis of cardiovascular diseases primarily relies on large-scale 12-lead ECG machines in hospitals. Therefore, early detection of abnormalities in ECG waveforms, combined with timely diagnosis and treatment, can effectively reduce mortality caused by cardiovascular diseases. While accurate, large-scale 12-lead ECG machines in hospitals are bulky, not portable, and can only record signals for short periods. Owing to the latent nature of many cardiac diseases, these limitations lead to difficulties in monitoring cardiac abnormalities in a timely manner. Portable ECG monitoring devices have attracted growing interest in recent years4. The design and development of portable ECG monitoring systems hold significant clinical value, enabling real-time ECG monitoring outside traditional clinical settings. At the same time, artificial intelligence (AI), especially neural networks, has progressed quickly.Research on intelligent ECG detection and classification to assist in cardiovascular disease diagnosis has grown explosively, with numerous new technologies and clinical applications emerging annually5. Combining portable ECG monitors with intelligent diagnostics is poised to become a major trend in both research and practical application. The portable ECG monitoring and diagnostic device proposed in this study incorporates collaborative hardware–software design, Wi-Fi–based data transmission, and deep learning–based ECG classification algorithms deployed on a host computer. This system helps doctors monitor and diagnose heart rhythms remotely, which can lead to faster and more accurate diagnosis of cardiac conditions. Thus, the research presented in this paper holds significant practical importance and application potential. This work aims to develop a portable ECG monitoring and intelligent diagnostic system capable of addressing the limitations of conventional clinical ECG equipment. The objective of this study is to provide continuous heart monitoring, real-time data transfer, and automated rhythm analysis outside the hospital, improving how quickly and reliably we can detect heart problems. Building upon recent advancements in embedded sensing, wireless communication, and deep learning, this paper introduces an integrated hardware–software solution that combines portable ECG acquisition, Wi-Fi–based signal transmission, and a host-computer deep learning framework for ECG classification. The proposed system establishes a complete workflow from real-time signal collection to automated diagnostic support, demonstrating its potential to enhance remote cardiac monitoring, facilitate early detection of abnormalities, and provide practical value for intelligent healthcare applications. Related work Recent advances in sensors and wearables have shifted ECG monitoring from the clinic to wireless, remote, real-time use. Since Norman J. Holter invented the Holter monitor6, fifty years of development have made portable ECG acquisition more convenient, accurate, and intelligent. Numerous research institutions and companies worldwide have conducted extensive research in the field of portable and wearable ECG monitoring technology. In 2009, Brown7 and colleagues from the Holst Centre in the Netherlands designed a system for monitoring various physiological parameters. This system featured a miniaturized, low-power universal wireless sensor module capable of monitoring various physiological indicators through ultra-low-power sensors. Sensors placed on the chest were used to monitor ECG signals, while sensors worn on the wrist could record skin conductance and body surface temperature. In 2012, S. Nemati8 and colleagues from McMaster University in Canada created a wearable ECG sensor. The sensor used the ANT protocol as a low-data-rate wireless module to reduce sensor power consumption and size. Small capacitive electrodes were integrated with signal processing and transmission boards into a cotton T-shirt using standard two-layer printed circuit board design techniques. The resulting system was compact, thin, and energy-efficient, yet it produced ECG signals on par with those from standard adhesive electrodes. In 2016, F. A. Castano9and colleagues from the University of Antioquia in Colombia designed and developed a portable wearable monitoring device capable of monitoring multiple physiological parameters. This device integrated multiple sensors into clothing, wirelessly streaming data to a portable unit and enabling patients to go about their daily routines during monitoring. While it could track ECG and heart rate, the device’s filtering failed to adequately remove motion artifacts. This noise hampered further signal analysis and limited the device’s practical use. On March 1, 2020, Arizton Advisory & Intelligence, a renowned consulting firm in market research, released the report “Wearable ECG Devices Market Size, Share, Industry Analysis & Growth Forecast 2027”. The report mentioned that the forms of wearable ECG monitoring devices are becoming increasingly diverse, including smartwatches, patches, bands, necklaces, clothing, rings, and other forms. These options vary in their electrodes, battery life, processing power, and connectivity, offering users greater flexibility in wearing options10. As portable technology advanced, research into automatically classifying arrhythmias also grew quickly. Arrhythmia classification typically involves three steps: preprocessing the data, extracting features, and building a classification model. Among these, feature extraction is a crucial component of arrhythmia classification, as the accuracy of feature extraction directly affects the accuracy of the classification results. Methods for extracting features from ECG waveforms fall into two main categories: manual feature engineering and automated feature learning using deep learning. Manual extraction algorithms include transfer learning, principal component analysis, and others11,12. The manual approach to feature extraction requires coefficient transformation analysis of the ECG before feature extraction and classification.This labor-intensive process is prone to human error and inconsistency, and its complexity has led researchers to move away from it. Compared to traditional methods, deep learning-based approaches can be directly applied to classification tasks without the need for additional feature extraction, making the process simpler and more efficient, especially in achieving high accuracy on tasks with large-scale data. In 2016, Kiranyaz et al.13 designed a one-dimensional CNN-based ECG classification and monitoring system that could rapidly and accurately classify long-duration ECG recordings. In 2018, Oh et al.14 proposed an automated arrhythmia diagnosis system combining convolutional neural networks (CNN) to capture spatial patterns with long short-term memory (LSTM) to model temporal dependencies in the ECG. This system demonstrated high classification performance when handling variable-length data, achieving an accuracy rate of 98.10% through a ten-fold cross-validation strategy. In 2018, Yildirim et al.15 introduced a novel model based on deep bidirectional LSTM (BiLSTM) networks paired with a wavelet sequence layer (DBLSTM-WS). The wavelet layer generated an additional informative representation of the input signal, which significantly boosted the classification performance of the core DLSTM network. The results showed that the DBLSTM-WS model achieved a high recognition performance of up to 99.39%. In 2020, Dokur et al.16 used a CNN to classify eleven different ECG heartbeat types from the MIT-BIH arrhythmia database. They trained the network using Walsh functions, which allowed them to maintain a compact model architecture without sacrificing classification accuracy. In 2023, Khiem et al.17 designed a deep learning system called ECG, which accurately identified multiple cardiovascular abnormalities using only three ECG leads (I, II, and VI). The ECG system outperformed most existing ECG classification methods in 3-lead ECG classification tasks, with higher F1 scores, lower complexity, and greater compactness. However, its multi-input architecture requires large datasets for training, and working with such datasets brings computational and storage cost challenges. In addition to the aforementioned representative works, Table 1 summarizes other deep learning recognition models. Table 1Summary of classification models and their average accuracies.AuthorClassification ModelTypesAverage Accuracy(%)Jun et al.182D-CNN1199.05Atal et al.19DCNN293.19Liu et al.20LSTM1199.05Mostayed et al.21Bi-directional LSTM9N/AGuo et al.22DenseNet+GRUN/A95.60Bouchouareb et al.23RBF+SVM6N/AYang et al.24PCANet597.77Hou et al.25LSTM+AE599.41 Summary of classification models and their average accuracies. The concept of “dilated convolution” was first introduced by Chen et al. in 2014. After a decade of development, it is now widely used in deep learning. An increasing number of studies have confirmed that dilated convolution not only performs excellently in tasks such as image segmentation and object detection but also has the potential to be applied in more areas, such as video processing and natural language processing. This will further promote the comprehensive development of deep learning technologies26. In this work, we employ a hybrid dilated convolution model for classification. We detail its architecture in the Methods section. Methods This work integrates portability and diagnostic intelligence by designing a portable monitoring and diagnostic device that uses a hybrid dilated convolution model. This approach aims to verify the feasibility of combining these two aspects and to analyze the performance of the device. In this section, we discuss the methodology of our research in detail. Overall system structure The system adopts a two-tier architecture comprising a portable acquisition terminal and a host computer-based processing platform (Fig. 1). The portable terminal captures ECG signals using standard Ag/AgCl adhesive electrodes connected to an AD8232 analog front-end chip, which performs hardware-level signal conditioning including a dual-pole high-pass filter ( Hz) for baseline drift suppression, a dual-pole low-pass filter ( Hz) for high-frequency noise rejection, and a right-leg drive amplifier for common-mode rejection, achieving an overall gain of 1100. The conditioned analog signal is digitized by an ESP32 microcontroller via its integrated 12-bit ADC at a fixed sampling rate of 200 Hz, after which a software-based IIR filter is applied on the ESP32 as a second denoising stage. The filtered data is then packetized into 256-byte payloads and transmitted to the host computer in real time over a Wi-Fi/TCP link with an average latency of approximately 20 ms and a throughput of approximately 1.5 Mbps. The entire portable terminal measures 80 mm × 100 mm and weighs approximately 150 g. Overall system structure. On the host computer side, a multi-threaded Qt5 application receives and processes the incoming TCP data stream. The main thread parses the packets and renders the real-time ECG waveform together with vital signs on the graphical interface, while a dedicated worker thread performs the third denoising stage using a Hierarchical Kalman Filter (HKF) that employs patient-specific prior model fitting and online Kalman smoothing to remove residual noise while preserving diagnostically critical waveform features such as the QRS complex and T-wave morphology. The HKF-filtered signal is then segmented into individual heartbeat cycles via R-peak detection and forwarded to an external Python inference engine, where each 1D beat segment is converted into a standardized 128 × 128 2D grayscale image and classified by the proposed hybrid dilated convolutional network with spatial-channel hybrid attention, yielding one of eight rhythm categories. The diagnostic result is returned to the Qt interface and displayed alongside the corresponding ECG waveform in real time, providing automated clinical decision support. Design of ECG acquisition front-end circuit ECG signals are weak and easily corrupted by noise. The acquisition process itself is vulnerable to environmental interference, which introduces noise and complicates subsequent analysis. Therefore, effective denoising is a critical step in ECG acquisition. Common types of noise in ECG signals include baseline drift, electromyographic (EMG) interference, and power frequency interference27. Baseline drift refers to the superposition of a low-frequency signal on the original signal, causing the original signal to exhibit a slow, gradual drift, which is usually generated by the rhythmic breathing or limb movement of the subject being measured. If not removed, it can severely distort the signal and hinder accurate analysis. EMG interference is mainly caused by the tremor of muscle fibers, which leads to changes in the potential of the body surface and affects the potential difference measured by the surface electrode patch. EMG interference introduces small-amplitude artifacts into the collected ECG signal, degrading its quality. Power frequency interference originates from power supply equipment, where electromagnetic (EM) induction caused by unstable AC current degrades the acquisition quality28. The ECG acquisition circuit designed in this paper is depicted in Fig. 2a. The circuit employs a highly integrated bioelectric signal acquisition chip, AD8232, which incorporates filtering and amplification circuits, as the front-end chip. This system achieves a dual-pole high-pass filter with a cutoff frequency of 0.5 Hz and a dual-pole low-pass filter with a cutoff frequency of 41 Hz, with an overall system gain of 1100. The internal structure of the AD8232 chip is shown in Fig. 2b, which primarily consists of a high-pass filter circuit, a low-pass filter circuit, and a right-leg drive circuit. The acquisition circuit and the internal structure of the AD8232 circuit. a) The design of AD8232 circuit. b) The internal structure and principle of AD8232. c) High-pass filter. d) Low-pass filter. e) Right leg drive circuit. The second-order dual-pole high-pass filter is shown in Fig. 2c. The first stage is an AC-coupling network: blocks the DC offset from the electrode–tissue half-cell potential, while provides the DC bias path to the internal reference voltage (), setting the input common-mode level. The second stage, formed by and together with the integrated operational amplifier, constitutes an active feedback network that sharpens the roll-off to −40 dB/decade and determines the filter’s quality factor. With and , the −3 dB cutoff frequency is The equal-component design simplifies the bill of materials (BOM) while maintaining a flat passband response above the corner frequency, effectively suppressing baseline drift caused by respiration and subject movement. The dual-pole Sallen–Key low-pass filter (Fig. 2d) employs the rail-to-rail operational amplifiers integrated within the AD8232. In this topology, and form the first passive pole at the non-inverting input, while and together with the amplifier constitute the second-order feedback path that determines the filter’s damping characteristic. The Sallen–Key architecture is chosen here for its high input impedance and low output impedance, which allow direct cascading without additional buffering stages. The cutoff frequency and the passband gain are respectively given by Here and jointly set the corner frequency together with and , while and define the non-inverting gain of the amplifier stage. The component values are selected to yield a Butterworth (maximally flat) response in the passband, providing a clean roll-off above 41 Hz that attenuates EMG artifacts and power-line interference before the signal reaches the ADC input. The right-leg drive (RLD) circuit, shown in Fig. 2e, senses the common-mode voltage at the junction of two matched summing resistors (, ) connected to the instrumentation amplifier inputs. This common-mode signal is inverted, amplified by the integrated RLD amplifier with a gain of , and fed back to the subject’s body through a current-limiting resistor . The negative feedback actively drives the body potential toward the reference level, cancelling common-mode interference at its source. The current-limiting resistor ensures patient safety by restricting the maximum injected current to well below the IEC 60601 limit of 50 μA, while also preventing potential oscillation in the feedback loop. With a properly chosen RLD gain, the system’s common-mode rejection ratio (CMRR) is significantly improved over the intrinsic CMRR of the instrumentation amplifier alone, making the front-end robust against 50/60 Hz power-line coupling and other environmental common-mode disturbances. In the complete acquisition front-end (Fig. 2a), the ECG signal propagates through four cascaded stages. First, the electrode inputs are AC-coupled via to the instrumentation amplifier (IA), where the differential cardiac signal (typical amplitude 0.5–5 mV) is pre-amplified with a fixed gain set by an external gain-setting resistor . Second, the pre-amplified signal passes through the dual-pole high-pass filter that suppresses baseline wander. Third, the signal enters the dual-pole Sallen–Key low-pass filter that rejects high-frequency noise beyond the ECG bandwidth. Finally, the conditioned signal is buffered and output to the ESP32’s integrated 12-bit ADC. The total system gain of 1100 is the product of the IA gain, the low-pass filter passband gain (), and the output buffer stage, ensuring that the sub-millivolt ECG signal is mapped to a voltage range compatible with the ADC input dynamic range. The RLD circuit operates in parallel with this signal chain, providing continuous common-mode correction throughout the acquisition. Design of neural networks Network architecture As illustrated in Fig. 3, the proposed network is organized into five sequential processing blocks followed by a classification head. Block 1 employs standard convolutions (r=1) to extract low-level morphological features from the input ECG image. Block 2 and Block 3 constitute the hybrid dilated convolution (HDC) module: Block 2 applies dilated convolutions with r=2 (128 filters), while Block 3 further expands the receptive field with r=4 (256 filters). By stacking increasing dilation rates with interleaved max-pooling layers to ensure continuous spatial coverage, these two blocks jointly achieve dense receptive-field coverage while avoiding the gridding effect. Block 4 is the hybrid attention module that refines the feature maps via parallel spatial and channel attention branches. Block 5 compresses the feature maps using global average pooling (GAP) and performs final classification through a fully connected layer with Dropout regularization and a Softmax output. The detailed configuration of each block, including tensor dimensions at every stage, is provided in the “Network Configuration and Data Flow” subsection. Dilated convolution-hybrid attention mechanism structure. Our network includes a Hybrid Attention (HA) module to capture relevant information from both the spatial layout and the channel dimensions of the ECG image representations. As shown in Fig. 3, the HA module is implemented by a spatial–channel attention block inserted after the last convolutional layer. Specifically, it has two parallel branches. One performs channel attention via global pooling and fully-connected layers, while the other performs spatial attention by learning a spatial attention map using a convolutional operation. The outputs of both branches are then combined and applied to the input feature map through element-wise multiplication, allowing the network to focus on the most informative features both spatially and across channels. This dual attention mechanism helps to enhance the performance of the network by adaptively emphasizing the most relevant features in the ECG images. Data sources and preprocessing In this study, the MIT-BIH Arrhythmia Database was adopted as the primary data source. The database offers high-quality recordings and rigorous annotations, and serves as a standard benchmark in the field, making it ideal for developing and testing ECG classifiers. Using Python libraries, we extracted the raw one-dimensional ECG signals from the database, along with their annotations and the R-peak location for each heartbeat. The annotation format of the MIT-BIH database includes the positions of the R-peaks and the associated annotation codes. These labels clearly specify the category of each heartbeat and provide reliable ground truth for subsequent classification experiments. To ensure compatibility with widely adopted ECG evaluation protocols, the eight-class output of our model was further mapped to the five-class scheme recommended by the ANSI/AAMI EC57 standard. The specific mapping of the heartbeat types to AAMI classes is shown in Table 2, which includes categories such as Normal (N), Supraventricular ectopic (S), Ventricular ectopic (V), Fusion (F), and Unknown/paced/unclassifiable (Q). Table 2Abbreviations, descriptions, and AAMI-class mappings of heartbeat types.AbbreviationDescriptionAAMI ClassNNormal beatNLBBBLeft bundle branch block beatNRBBBRight bundle branch block beatNAPCAtrial premature contractionSPVCPremature ventricular contractionVPABPremature Atrial BeatSVEBVentricular ectopic beatVVFWVentricular fusion beatF Abbreviations, descriptions, and AAMI-class mappings of heartbeat types. To satisfy the input requirements of the two-dimensional convolutional neural network (2D-CNN) model, we designed and implemented a Python preprocessing module that converts the raw 1D ECG sequences into standardized 2D image representations. The scientific rationale for opting for a 2D-CNN architecture over a native 1D-CNN is primarily driven by the morphological nature of clinical ECG analysis. Arrhythmia diagnosis heavily depends on the geometric shape and structural contours of the waveform (e.g., QRS complex and T-wave). The 1D-to-2D transformation explicitly converts temporal voltage variations into distinct spatial edges and structural textures, thereby allowing the 2D convolutional kernels to extract these morphological anomalies more effectively. Furthermore, mapping varying-length 1D heartbeat segments into a fixed 128 × 128 pixel matrix inherently provides time-scale normalization, circumventing the need for signal truncation or zero-padding. Crucially, this 2D representation synergizes perfectly with our proposed Hybrid Dilated Convolution and Spatial Attention modules, enabling the network to spatially localize pathological waveform features on a 2D plane. The complete preprocessing workflow is summarized in Algorithm 1. Evaluation protocol and inter-patient split In this study, a strict inter-patient evaluation protocol was enforced to prevent intra-patient data leakage and to ensure that model performance reflects real-world clinical deployment, where ECG classification systems must generalize to new patients. Following the ANSI/AAMI EC57 standard, all beats in the MIT-BIH Arrhythmia Database were mapped into five AAMI classes (Normal, Supraventricular ectopic, Ventricular ectopic, Fusion, and Unknown/Paced/Unclassifiable). To ensure complete separation between patients, all data from a single patient was kept entirely within one of three data splits. A fixed test set was established, consisting of a predefined set of patient IDs that remained strictly isolated throughout the study and was used solely for final performance evaluation. The remaining patients were used for training and validation. Training and Validation via Patient-Level 10-Fold Cross-Validation For the training and validation phases, a subject-independent 10-fold cross-validation scheme was employed. The patients not in the final test set were divided into ten groups, with no patient appearing in more than one group. In each cross-validation cycle, nine folds were used for training and the remaining fold was used for validation. This method gives a reliable performance estimate across different patient groups while keeping the data for each patient entirely separate. Fixed Test Set The test set consisted of the following patient IDs: 100, 103, 105, 111, 113, 117, 121, 123, 200, 202, 210, 212, 213, 214, 219, 221, 222, 228, 231, 232, 233, 234 100, 103, 105, 111, 113, 117, 121, 123, 200, 202, 210, 212, 213, 214, 219, 221, 222, 228, 231, 232, 233, 234 These subjects were never used in model training or hyperparameter selection. This hybrid strategy—fixed subject-independent test set combined with patient-level 10-fold cross-validation for training and validation—ensures a fair evaluation and prevents data leakage, thereby better reflecting clinical generalizability. Hybrid dilated convolution In a standard convolution, all elements of the kernel operate on adjacent pixels in the input. This results in a slowly growing receptive field, so capturing long-range context needs very deep networks or large kernels. The essential difference between regular convolution and dilated convolution is whether the convolution kernel contains dilation gaps. In a regular convolution, adjacent kernel elements operate on adjacent pixels. In contrast, a dilated convolution inserts fixed intervals, i.e., a dilation rate r, between kernel elements, thereby expanding the receptive field without increasing the number of parameters or computational cost. As shown in Fig. 4, different dilation rates (e.g., r = 1, r = 2, and r = 3) lead to different receptive fields. When r = 1, the operation is equivalent to a standard convolution. When r> 1, the kernel “skips” pixels in the spatial domain, enabling the model to capture wider contextual information while preserving the original resolution. The Receptive field of convolutional kernels at different dilation rates. The effective size of a dilated convolution kernel and the corresponding receptive field can be expressed as where is the size of the original kernel, d is the dilation rate, is the receptive field at layer m, and is the stride at layer i. Although dilated convolutions effectively enlarge the receptive field, stacking several layers with the same dilation rate may cause a phenomenon known as the “gridding effect”. This occurs because when multiple layers use the same dilation rate, their receptive fields do not overlap completely, leaving gaps. Specifically, when a dilation rate r is applied, the kernel elements are spaced r pixels apart. If this spacing is consistent across multiple layers, some pixels in the image may never be involved in the convolution computation for certain central positions, creating a grid-like pattern where regions of the input image do not contribute to the output. This disrupts the continuity of the feature map and can cause the loss of fine local details, which are especially important in ECG signals for accurate classification. To alleviate this issue, we adopt hybrid dilated convolution (HDC), which combines multiple dilation rates within the same convolutional module. In this design, different dilation rates are applied to different convolutional layers within the same stack, and interleaved max-pooling operations between successive dilated layers prevent uniform spacing of kernel gaps. This strategy ensures a more continuous coverage of the input space. As a result, each layer can capture different spatial relationships and features, avoiding the grid pattern that causes information gaps. By combining multiple dilation rates, HDC enables more comprehensive feature extraction across a wide range without losing local details, producing richer and more robust features for ECG analysis. The HDC module proposed in this paper is illustrated in Fig. 3. It consists of two branches with dilation rates of 2 and 4, respectively. The proposed hybrid dilated convolution module not only addresses the limitations of traditional dilated convolutions but also integrates seamlessly into the overall network, enhancing feature representation while keeping the number of parameters manageable. Hybrid attention mechanism Based on29,30, we use a hybrid attention module (Fig. 3) to capture long-range dependencies across both spatial positions and feature channels. The hybrid attention module is composed of spatial and channel attention modules in parallel, emphasizing interdependent feature mappings on spatial and channel axes for the input feature maps. The feature maps processed by both attention modules are then fused through element-wise addition to yield output feature maps with enhanced feature representation. The spatial attention mechanism primarily focuses on object localization, followed by the selection of the localized targets, choosing the correct localization points, and discarding erroneous ones, thereby directing attention to the correct locations, reducing the model’s focus on unnecessary pixels, and retaining key image information. The channel attention mechanism identifies which feature types are most important, learning to emphasize the most relevant channels. The distinction between the two lies in their focus on image feature information from different dimensions and perspectives; the channel attention mechanism is divided into Squeeze and Excitation operations. The Squeeze operation summarizes each feature channel into a single value using global average pooling, capturing its overall importance. The Excitation operation extracts effective information from ECG across channel dimensions, calculating the degree of attention to ECG across various channels. The spatial-channel attention mechanism module combines the spatial attention mechanism with the channel attention mechanism to obtain more precise feature maps. H, W, and C represent the dimensions of length, width, and the number of channels in the feature map, respectively. If x is the input feature map, i and j are the positions of two pixels in the feature map, and y is the output feature map, then the following expressions hold: Here, represents the correlation function between pixels, is used for the functional transformation of input information, and C(x) denotes the normalization function. The weight matrix is defined as , and and can be obtained from the following equations: In the proposed network, these attention operations are implemented within Block 4 (Fig. 3). Specifically, the channel attention branch applies global average pooling (Squeeze) followed by a two-layer fully-connected network (Excitation) to produce channel-wise weights, while the spatial attention branch employs a 1× 1 convolutional layer to generate a spatial attention map. The two sets of weights are fused via element-wise addition and multiplied with the input feature map, preserving the dimensionality while selectively enhancing diagnostically salient features such as the QRS complex and T-wave contours. To quantify the efficiency of the proposed 2D-CNN architecture, we report its model size, floating-point operations (FLOPs), inference latency, and memory footprint on the target deployment platform. Network configuration and data flow To clarify the specific operations and the flow of data within the proposed architecture (as illustrated in Fig. 3), the network is logically divided into five main processing blocks, followed by a classification head. The input to the network is a standardized 2D ECG image with dimensions of . Block 1 (Initial Feature Extraction): The first block consists of two standard convolutional layers (dilation rate r=1) with 64 filters of size 3 × 3, each followed by an Exponential Linear Unit (ELU) activation and Batch Normalization. This block focuses on extracting low-level morphological features from the raw ECG images. The output feature map retains the spatial resolution of , which is then downsampled to via a 2 × 2 Max Pooling layer. Block 1 (Initial Feature Extraction): The first block consists of two standard convolutional layers (dilation rate r=1) with 64 filters of size 3 × 3, each followed by an Exponential Linear Unit (ELU) activation and Batch Normalization. This block focuses on extracting low-level morphological features from the raw ECG images. The output feature map retains the spatial resolution of , which is then downsampled to via a 2 × 2 Max Pooling layer. Block 2 (HDC Stage 1): To expand the receptive field without losing resolution, Block 2 employs two dilated convolutional layers with a dilation rate of r=2 and 128 filters. This allows the network to capture wider contextual features of the heartbeat waveform. After ELU and Batch Normalization, the output is , which is subsequently max-pooled to . Block 2 (HDC Stage 1): To expand the receptive field without losing resolution, Block 2 employs two dilated convolutional layers with a dilation rate of r=2 and 128 filters. This allows the network to capture wider contextual features of the heartbeat waveform. After ELU and Batch Normalization, the output is , which is subsequently max-pooled to . Block 3 (HDC Stage 2): The data then flows into Block 3, which further increases the receptive field using two dilated convolutions with a dilation rate of r=4 and 256 filters. By stacking increasing dilation rates sequentially (from r=2 in Block 2 to r=4 in Block 3), the network effectively forms a Hybrid Dilated Convolution (HDC) structure that mitigates the gridding effect. The output feature map reaches a highly semantic state with dimensions of . Block 3 (HDC Stage 2): The data then flows into Block 3, which further increases the receptive field using two dilated convolutions with a dilation rate of r=4 and 256 filters. By stacking increasing dilation rates sequentially (from r=2 in Block 2 to r=4 in Block 3), the network effectively forms a Hybrid Dilated Convolution (HDC) structure that mitigates the gridding effect. The output feature map reaches a highly semantic state with dimensions of . Block 4 (Hybrid Attention Module): The feature map is fed into the Spatial-Channel Attention Block. This module operates without altering the tensor dimensions. It calculates attention weights across the 256 channels and the spatial domain in parallel, merging them via element-wise addition, and applies them back to the input feature map to highlight diagnostically critical regions. The refined map is then downsampled to by a final Max Pooling layer. Block 4 (Hybrid Attention Module): The feature map is fed into the Spatial-Channel Attention Block. This module operates without altering the tensor dimensions. It calculates attention weights across the 256 channels and the spatial domain in parallel, merging them via element-wise addition, and applies them back to the input feature map to highlight diagnostically critical regions. The refined map is then downsampled to by a final Max Pooling layer. Block 5 & Classification Head: Instead of flattening the tensor—which would drastically increase the parameter count—the network utilizes a Global Average Pooling (GAP) layer to compress the spatial dimensions into a 1D vector of length 256. This vector is passed through a fully connected Dense layer (256 units, ELU, BN) and heavily regularized using a Dropout layer with a rate of 0.5 to prevent overfitting. Finally, a Dense layer with a Softmax activation outputs the probability distribution across the target ECG categories. Block 5 & Classification Head: Instead of flattening the tensor—which would drastically increase the parameter count—the network utilizes a Global Average Pooling (GAP) layer to compress the spatial dimensions into a 1D vector of length 256. This vector is passed through a fully connected Dense layer (256 units, ELU, BN) and heavily regularized using a Dropout layer with a rate of 0.5 to prevent overfitting. Finally, a Dense layer with a Softmax activation outputs the probability distribution across the target ECG categories. Model size. The final network contains a total of 1,246,793 trainable parameters, corresponding to approximately 1.25 million parameters. In single-precision floating point (FP32), the model weights require about 4.8 MB, which is relatively light compared to many existing ECG classification models. FLOPs. For an input resolution of , the convolutional and fully connected layers together require approximately 2.46 GMACs per beat, which corresponds to about 4.91 GFLOPs when a multiply–add operation is counted as two FLOPs. Inference latency. Runtime performance was evaluated on the target host equipped with an NVIDIA GeForce RTX 4050 Laptop GPU (6 GB VRAM). Processing the entire MIT-BIH test set (49,468 beats) took 24 minutes 51 seconds, a throughput of about 14.4 beats/s. This corresponds to an average inference latency of about 69 ms/beat (including data loading and framework overhead), which satisfies the real-time requirements of continuous ECG monitoring applications. Memory footprint. During inference, the memory occupied by the model weights is approximately 4.8 MB in FP32 format, which is negligible relative to the 6 GB VRAM available on the RTX 4050 Laptop GPU. Even when accounting for intermediate feature maps and framework overhead, the overall memory footprint remains modest, making the proposed model suitable for deployment on mainstream laptop GPUs and other edge devices with moderate memory capacity. Design of host computer software We developed the host computer software with Qt5, which provides a stable framework for the graphical user interface. It uses the Qt Charts module for real-time waveform display and Qt’s built-in socket library for TCP communication with the wearable device. When a raw 1D ECG signal arrives, the host computer parses the data stream in the main thread and displays basic physiological information (e.g., body temperature and the original ECG waveform) on the interface. To keep the interface responsive, the signal is passed to a Qt child thread for signal filtering, analysis, and rhythm interpretation. This child thread further invokes a Python inference script to perform beat-level processing and deep learning–based classification. The Python module is responsible for converting the incoming 1D ECG signal into a standardized 2D image representation suitable for CNN-based inference. As summarized in Algorithm 1, R-peaks are detected using the BioSPPy implementation of the Christov algorithm, and the continuous ECG recording is segmented into individual heartbeat cycles based on adjacent R-peak intervals. Each beat segment is then amplitude-normalized and plotted as a clean axis-free waveform image using Matplotlib. The resulting curve images undergo morphological preprocessing and are resized to a uniform resolution of 128 × 128 pixels using OpenCV, yielding a consistent 2D representation. These processed images are subsequently fed into the 2D-CNN classifier for rhythm identification, and the diagnostic results are returned to the Qt interface in real time for display. Conversion of 1D ECG Signal into 2D Image Representation. Host computer program flow chart. Main interface of the upper computer. Experiments Hierarchical Kalman filter experiment Figure 7 shows the filtered results for a test signal. We took a clean ECG segment from the MIT-BIH database, added simulated Gaussian noise following a power-law colored noise model under a controlled SNR setting, and then processed it with three different filtering methods: the Extended Kalman Filter (EKF)31, a hybrid IIR+FIR filtering approach, and the Hierarchical Kalman Filter (HKF)32. Compared to the EKF and IIR+FIR methods, the HKF achieves superior noise reduction while preserving the key features of the ECG waveform. As illustrated, the EKF offers moderate noise reduction but may exhibit instability in dynamic heart rate variations, while the IIR+FIR method is effective in general smoothing but tends to attenuate critical anomaly features due to its inherent phase delay. In contrast, the HKF maintains a balance between denoising and feature preservation, making it more suitable for accurate anomaly detection in heart rate signals. Zoom-in of the boxed region in Fig. 7. Comparison of Hybrid Kalman Filter, FIR, and IIR Filtering Performance. Holter ECG experiment Figure 10 shows the physical ECG acquisition unit and a screenshot of the diagnostic results on the host computer interface. As shown in Fig. 10, the system provides clear waveform feedback and accurate diagnostic information under normal physiological conditions. Both body temperature and heart rate are detected within standard ranges. Waveforms and diagnostic results displayed. In addition, Fig. 10 shows the physical dimensions of the developed ECG terminal, which measures 100 mm × 80 mm, with a total weight of approximately 150 g including the electrodes. The compact and lightweight form factor significantly enhances portability, making the device suitable for daily long-term physiological monitoring. Heart rate testing experiment We tested heart rate detection accuracy using a programmable ECG simulator that generates signals at preset beats-per-minute (BPM) values. During the test, heart rate data were refreshed every 3 seconds and continuously recorded for 1 minute. For each reference setting (50, 60, 70, 100, 110, and 120 BPM), 20 consecutive measurements were acquired and plotted to examine measurement consistency, as shown in Fig. 9. Heart rate measurements under different reference BPMs. Results show that for heart rates below 100 BPM, the measurement error stays under 2%, with very little variation. For rates above 100 BPM, we observed more fluctuation and a gradual drop in accuracy. Nevertheless, even at higher reference values, the error is constrained within 4%. Two factors explain the higher error at elevated heart rates. First, our fixed 200 Hz sampling rate provides fewer data points per heartbeat, making peak detection less stable. Second, the AD acquisition routine in the embedded program, designed with a nominal 5 ms execution period, experiences practical timing jitter of approximately 80 µs, introducing additional variability. Signal processing and system evaluation This experiment tested the complete system performance, from signal acquisition and denoising to parameter extraction. ECG signals were processed through a HKF followed by an infinite IIR filter. The extracted heart rate values were compared against ground-truth measurements. Across multiple test conditions, the computed BPM values maintained errors within , demonstrating the robustness and reliability of the overall signal processing pipeline. Network transmission experiment To assess the communication performance between the embedded ECG terminal and the host computer, a network transmission test was conducted over a Wi-Fi connection using the TCP protocol. The evaluation metrics included end-to-end delay, throughput, and transmission integrity. Data packets were transmitted with a fixed payload size, and both transmitting and receiving buffers were configured to 256 bytes. Results show reliable real-time transmission with an average delay of 20 ms and negligible packet loss. The throughput is maintained at about 1.5 Mbps under typical operating conditions. Although further optimization of network parameters has not yet been performed, the current configuration ensures stable ECG data transmission and supports real-time monitoring as well as cloud-based interaction. These findings confirm that the proposed system is suitable for practical long-term health management applications. Training details and implementation All models were implemented in Python using TensorFlow 2.10 and trained on an NVIDIA GeForce RTX 4050 Laptop GPU (6 GB VRAM) with GPU memory growth enabled. During training, we loaded 2D ECG images, converted them to RGB, and resized to 128× 128 pixels, while labels were encoded as eight-class one-hot vectors. For evaluation, the model outputs are mapped to the five AAMI classes (N, S, V, F, Q) per the ANSI/AAMI EC57:2012 standard. The proposed network was optimized using the Adam optimizer with a fixed learning rate of , a batch size of 16, and categorical cross-entropy loss; all experiments were run for 100 epochs without early stopping. No geometric or intensity-based data augmentation was applied in order to isolate the contribution of the model architecture and the 1D-to-2D conversion pipeline. Critically, we enforced a strict inter-patient protocol: the patients in the training, validation, and test sets were completely separate. Specifically, DS2 was held out as a fixed test set for final evaluation, while the training set (DS1) was further partitioned via a subject-independent 10-fold cross-validation scheme. In each cycle, nine patient groups from DS1 trained the model and the remaining one group validated it. Custom Python generators handled on-the-fly data streaming and batch construction. A custom callback recorded training metrics and saved intermediate checkpoints, and final model weights were stored for subsequent testing and analysis. Classification experiment AAMI EC57 five-class standard evaluation The MIT-BIH Arrhythmia Database exhibits a pronounced class imbalance. Under the strict inter-patient split, the DS2 test set contains the 49,468 beats from the eight heartbeat types recognized by the model, with the following AAMI distribution: N (Normal) accounts for 44,022 beats (89.0%), S (Supraventricular) for 1,838 beats (3.7%), V (Ventricular) for 3,221 beats (6.5%), F (Fusion) for 387 beats (0.8%), and Q (Unknown/paced) has no corresponding beats in the eight-class model output. Accuracy alone is therefore an insufficient performance measure, as a trivial classifier that predicts the dominant N class for every beat would reach 89% accuracy. To provide a meaningful and balanced assessment, we report per-class sensitivity (Sen), specificity (Spe), positive predictive value (Ppr), F1-score, and Matthews Correlation Coefficient (MCC). These metrics are defined as follows: Here, TP, TN, FP, and FN denote true positives, true negatives, false positives, and false negatives, respectively. The eight-class model outputs were mapped to the five AAMI classes according to the mapping in Table 2 (N ← NOR/LBBB/RBBB, S ← APC/PAB, V ← PVC/VEB, F ← VFW, Q ← VFE). Table 3 reports the per-class metrics. Among the four evaluable classes, the model achieves strong performance: class N (F1 = 99.62%, MCC = 0.9649), class V (F1 = 98.43%, MCC = 0.9832), class F (F1 = 96.41%, MCC = 0.9642), and class S (F1 = 91.35%, MCC = 0.9121). The lower sensitivity of class S (86.24%) is consistent with the known challenge of supraventricular ectopic beat classification and reflects the high morphological variability within this category. Class Q is marked as non-evaluable because VFE beats (mapped to Q) are not covered by the current eight-class model output. The overall accuracy across the four evaluable classes is 99.28%, with a macro-averaged F1-score of 96.45% and a macro-averaged MCC of 0.9561 (computed over classes N, S, V, and F). The weighted F1-score (weighted by class support across N, S, V, and F) is 99.26%. These multi-metric results confirm that the proposed model delivers robust classification performance that is not merely driven by the dominant normal class. Table 3Classification performance under the AAMI EC57 five-class standard.ClassSen (%)Spe (%)Ppr (%)F1 (%)MCCN99.9494.3199.3099.620.9649S86.2499.9097.1291.350.9121V98.5199.8998.3698.430.9832F93.8099.9999.1896.410.9642QN/AN/AN/AN/AN/A Classification performance under the AAMI EC57 five-class standard. Comparison with existing models Table 4 compares the classification performance of the proposed hybrid dilated convolution model with several representative approaches discussed in the Related Work section. Given the large test set ( beats) and the use of strict inter-patient evaluation, the performance differences between the proposed model and the compared methods are statistically meaningful. Table 4Comparison of the proposed model with existing ECG classification methods.Classification ModelClassesACC (%)2D-CNN181199.05DCNN19293.19LSTM201199.05PCANet24597.77LSTM+AE25599.41CNN+LSTM14598.10DBLSTM-WS15599.39Lightweight 1D CNN33598.42Ours599.28 Comparison of the proposed model with existing ECG classification methods. Ablation study on dilated convolution and attention modules An ablation study was performed to quantify the individual contributions of the hybrid dilated convolution and hybrid attention modules to overall classification performance. Table 5 reports the AAMI five-class overall accuracy for each model variant. The results show that removing either the dilated convolution or the attention module leads to a modest change in overall accuracy, reflecting the complementary roles of the two components. Although the accuracy differences among variants are small, the full model provides a balanced combination of multi-scale feature extraction (via dilated convolution) and channel-spatial attention, which together improve per-class sensitivity on the clinically significant ventricular (V) and supraventricular (S) categories. Table 5Ablation study of different model variants under AAMI five-class evaluation.Model VariantACC (%)Baseline (2D CNN)99.25+ Dilated Conv99.18+ Attention99.08+ Dilated Conv + Attention (Full Model)99.28 Ablation study of different model variants under AAMI five-class evaluation. Conclusion Drawing on existing research, this work successfully combines portability with intelligent diagnosis in a single integrated ECG monitoring system. The portable acquisition terminal is designed to be compact, with overall dimensions controlled within 80 mm × 100 mm and a weight of approximately 150 g, facilitating continuous and comfortable wear for users. The acquisition terminal is linked to the host computer via Wi-Fi technology, and the acquired physiological data is wirelessly transmitted for subsequent filtering and classification through a hybrid dilated convolution model. The processed ECG waveforms and classification results are visualized on the host computer interface in real time, enabling medical staff to promptly detect any abnormal cardiac conditions. Experimental tests demonstrate that the AD8232 chip, combined with our software-based Hierarchical Kalman Filter, effectively processes ECG signals and suppresses environmental noise. The system maintains heart rate measurement accuracy within at rest and within during exercise. The host computer interface clearly displays ECG waveforms and classification results under both normal and abnormal cardiac conditions. Algorithmic evaluations under the AAMI EC57 five-class standard show that the proposed hybrid dilated convolution model achieves an overall accuracy of 99.28% with a macro-averaged F1-score of 96.45% and a macro-averaged MCC of 0.9561 across the four evaluable AAMI classes (N, S, V, F). While we do not claim absolute superiority in pure accuracy over all existing offline algorithms, our approach achieves highly competitive performance comparable to state-of-the-art models, with the distinct advantage of being successfully integrated into a fully deployable, lightweight hardware-software system. However, the system and methodology presented in this paper have clear limitations that leave room for future improvement. First, regarding the algorithmic design, converting 1D ECG signals into 2D image representations introduces additional computational and time overhead during the preprocessing stage, which may limit ultra-low-latency applications on severely resource-constrained microcontrollers. Exploring direct 1D-CNN architectures for edge-device deployment will be a key future direction. Secondly, the model currently classifies fewer heartbeat types than some comprehensive clinical studies; expanding this diagnostic range is a priority. Finally, from a hardware perspective, the wearable device could be further miniaturized through flexible printed circuit board (FPCB) design and more advanced System-on-Chip (SoC) integration to maximize long-term wearing comfort. Author contributions H.W. conceived the experiment and developed the methodology. Y.J. and C.Z. conducted the data preprocessing and model training. Z.S. analysed the results and prepared the visualizations. H.W. wrote the main manuscript text. All authors reviewed the manuscript. Funding No funding was received for conducting this study. Data availability The datasets generated and analysed during the current study are available in the MIT-BIH Arrhythmia Database, https://physionet.org/content/mitdb/1.0.0/ Code availability The source code for the microcontroller firmware is publicly available at https://github.com/jyh8877/ECG-IDCN/. Declarations 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 Associated Data Data Availability Statement The datasets generated and analysed during the current study are available in the MIT-BIH Arrhythmia Database, https://physionet.org/content/mitdb/1.0.0/ The source code for the microcontroller firmware is publicly available at https://github.com/jyh8877/ECG-IDCN/.