0% found this document useful (0 votes)
1 views54 pages

1 Rl 22 Final Report

The project report details the development of a CNN-based system for classifying arrhythmias using ECG image datasets, aimed at automating and optimizing the diagnostic process in healthcare. The system enhances accuracy and efficiency by minimizing human intervention and providing a user-friendly interface for healthcare professionals. It also emphasizes secure data management and remote access capabilities to improve patient outcomes and operational efficiency.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views54 pages

1 Rl 22 Final Report

The project report details the development of a CNN-based system for classifying arrhythmias using ECG image datasets, aimed at automating and optimizing the diagnostic process in healthcare. The system enhances accuracy and efficiency by minimizing human intervention and providing a user-friendly interface for healthcare professionals. It also emphasizes secure data management and remote access capabilities to improve patient outcomes and operational efficiency.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

VISVESVARAYA TECHNOLOGICAL UNIVERSITY

JNANA SANGAMA, BELAGAVI -590 014

A
Phase II Project Report
on
“CNN based Arrhythmia Classification using
ECG image Dataset”
Submitted for partial fulfillment of requirement for the award of Degree of

Bachelor of Engineering
in
Computer Science and Engineering
Submitted by

HARSHITHA U [1RL22CS044]
LAHARI D U [1RL22CS055]
LIKHITHA J [1RL22CS057]
MALLIKA S [1RL22CS061]
of
VII Semester
Under the guidance
Dr. BASAVARAJ S POL
Associate Professor

Department of Computer Science and Engineering


R. L. JALAPPA INSTITUTE OF TECHNOLOGY
Doddaballapur, Bangalore Rural Dist-561 203
2025-26
Sri Devaraj Urs Educational Trust (R.)
R. L. JALAPPA INSTITUTE OF TECHNOLOGY
(Approved by AICTE, New Delhi & Affiliated to VTU, Belagavi)
Kodigehalli, Doddaballapur- 561 203

Department of Computer Science And Engineering


CERTIFICATE

Certified that the project work entitled “CNN based Arrythmia Classification using
ECg images” carried out by Harshitha U, USN: [1RL22CS044], Lahari D U,
USN: [1RL22CS055], Likhitha J, USN: [1RL22CS057], Malliak S, USN:
[1RL22CS061], are bonafide students of R. L. Jalappa Institute of Technology, in partial
fulfillment for the award of Bachelor of Engineering in Computer Science Engineering of the
Visveswaraya Technological University, Belagavi during the year 2025-26. It is certified that
all corrections/suggestions indicated for internal assessment have been incorporated in the
report deposited in the department library. The project report has been approved as it satisfies
the academic requirements in respect of project work prescribed for the said degree.

Dr. Basavaraj S Pol Dr. Sunil Kumar R M Dr. P. VijayKarthik


Associate Professor Associate Professor & HOD Principal
Dept. of CSE Dept. of CSE RLJIT, Bangalore

Name Signature with date

Examiner 1:

Examiner 2:
ACKNOWLEDGEMENT

The satisfaction and euphoria that accompany the successful completion of


any task would be incomplete without the mention of the people who made it possible
and whose constant encouragement and guidance crowned our efforts with success.

We extend our deep sense of sincere gratitude to Dr. P VijayKarthik,


Principal, R L Jalappa Institute of Technology, Doddaballapur, for providing us an
opportunity to continue our studies.

We express our heartfelt sincere gratitude to Dr. Sunil Kumar R M, Head,


Department of Computer Science and Engineering, R L Jalappa Institute of
Technology, Doddaballapur, for his valuable suggestions and support and Project
Coordinator, Dr. Varalakshmi K R, Associate Professor, Dept. of CSE, R L Jalappa
Institute of Technology, Doddaballapur, Bangalore for their technical support to
implement our Project.

With profound sense of gratitude and acknowledge the guidance, support


extended by our project guide Dr. Basavaraj S Pol, Associate Professor, Department
of Computer Science and Engineering, R L Jalappa Institute of Technology,
Doddaballapur for her incessant encouragement and invaluable technical support which
has been of immense help in realizing this project.

Finally, we would like to thank all the faculty and supporting staff members of
Department of Computer Science and Engineering, R L Jalappa Institute of
Technology, Doddaballapur, for their support.

HARSHITHA[1RL22CS044]
LAHARI D U[1RL22CS055]
LIKHITHA J [1RL22CS057]
MALLIKA S [1RL22CS061]
ABSTRACT

The aim of the project is to design and develop an application that leverages the best software
engineering practices to implement a reliable and efficient system for classification of
arrhythmia using ECG image datasets. This system utilizes a Convolutional Neural Network
(CNN), a deep learning architecture which has a exceptional performance in image classification
tasks.

The purpose of the project’s system to automate and optimize the process of diagnosing cardiac
arrhythmias from ECG data, transitioning from manual evaluation to a robust and scalable
computerized solution. The system ensures that critical data is stored securely and can be
accessed, manipulated, and utilized for long-term medical analysis, assisting healthcare
providers in improving patient outcomes and operational efficiency.

The system architecture involves modules for preprocessing ECG data, converting it into image
representations, and utilizing CNN models for classification. By automating the classification
process, the system minimizes human intervention and errors, ensuring consistent and high-
quality results. Furthermore, it supports seamless data retrieval and avoids redundant entries,
promoting better resource utilization in clinical settings.

In essence, this project focuses on achieving high accuracy in arrhythmia detection while
ensuring usability and performance. It represents as our significant step toward integrating
advanced AI techniques into healthcare for better service delivery.

I
TABLE OF CONTENTS

Abstract I

Table Of Contents II

List Of Figure III

1 INTODUCTION 1-3

2 LITERATURE SURVEY 4-9

3 REQUIREMENTS 10-15
SPECIFICATION

4 SYSTEM DESIGN 11-21

5 IMPLEMENTATION 22-25

6 RESULT AND 26-28


DISCUSSION
7 FUTURE ENHANCEMENT 29-34

8 CONCLUSION 35-36

9 REFERENCES 37-38

10 APPENDICES 37-50

II
LIST OF FIGURES

Fig 1. Data Flow Diagram 18

Fig 2. Use Case Diagram 18

Fig 3. Epoch Training 30

Fig 4. Confusion Matrix 31

Fig 4. Confusion Matrix 42

Fig 6. User Interface 43

Fig 7. Output 47

III
CHAPTER 1

INTRODUCTION
The project titled “CNN-Based Arrhythmia Classification using ECG image dataset” focuses on
leveraging one of the deep learning (neural networks) techniques to enhance the diagnosis of
cardiac arrhythmias using electrocardiogram (ECG) image data. Cardiac arrhythmias are
irregularities in the heart's rhythm that can lead to severe health conditions if not diagnosed and
treated promptly. Current diagnostic approaches often rely on manual evaluation of ECG signals
by trained medical professionals. This process isn’t only time-consuming and labor-intensive but
also susceptible to errors, particularly in cases with subtle abnormalities. Thus, there is an urgent
need for an automated, reliable, and scalable system which can assist healthcare professionals in
diagnosing arrhythmias with greater precision and efficiency.

This project addresses the limitations of manual diagnostic process by developing a partially
computerized system that integrates state-of-the-art Convolutional Neural Networks (CNNs).
CNNs are a class of the deep learning models renowned for their ability to analyze and classify
visual data with high accuracy. In this context, the system processes raw ECG signals, converts
them into image representations, and classifies them into various arrhythmia categories. The
objective is to automate critical aspects of the diagnostic process, reducing the burden on medical
professionals and ensuring consistent, high-quality results.

Objectives and Scope


The primary aim of the project is to create a robust and user-friendly system that meets the needs
of healthcare organizations and improves patient outcomes. Key objectives include:

• Automation of Arrhythmia Diagnosis: Utilizing CNNs to classify ECG images


accurately, eliminating the need for manual analysis in routine cases.
• Data Management: Providing a centralized system to store and retrieve patient data,
historical diagnoses, and real-time results efficiently.

BE VII SEM Dept. of CSE , RLJIT 1 2025-2026


CNN-Based Arrhythmia Classification using ECG image dataset Introduction

• User Accessibility: Designing an interface that is intuitive and easy to use, enabling
medical professionals with levels of technical expertise to interact with system
seamlessly.

• Remote Access: Offering remote diagnostic capabilities to support healthcare providers


in diverse settings, particularly for time-sensitive cases.

This system is designed to handle diverse user roles, including administrators, healthcare
professionals, and patients. Each user group has tailored access to features and functionalities,
ensuring that the system caters to their specific needs. Administrators oversee the system’s
operation and ensure data security, healthcare professionals use the system for diagnosis and
patient monitoring, and patients and even doctors can access health reports and relevant medical
information through a secure interface.

System Features and Benefits


The CNN-Based Arrhythmia Classification System provides several essential features
• Automated Classification: By using CNN models, the system processes ECG data and
classifies arrhythmias with high accuracy, significantly reducing diagnostic time and
effort.
• Error Minimization: The application is designed to reduce errors.
• Scalability: The system can be scaled to handle large volumes of data, making it suitable
for hospitals, diagnostic centers, and research institutions.
• Remote Access and Integration: The system supports remote access, enabling
healthcare professionals to diagnose patients and review their records from any
location.
• Enhanced Resource Utilization: By automating routine tasks, the system allows
healthcare professionals to focus on critical medical decisions, optimizing resource
use within the organization.

Importance in Healthcare
Arrhythmia is a critical condition that requires timely and accurate diagnosis to prevent severe
complications. Traditional methods often fail to provide the level of consistency and

BE VII SEM [Link] CSE , RLJIT 2 2025-2026


CNN-Based Arrhythmia Classification using ECG image dataset Introduction

speed necessary in high-pressure clinical environments. By integrating CNN technology, this


project bridges the gap between traditional methods and modern AI-driven solutions. It not
only enhances the accuracy but also supports healthcare organizations in their strategic planning
by providing actionable insights and a scalable platform for patient management.

In conclusion, the CNN-Based Arrhythmia Classification System represents a significant step


forward in the application of AI to healthcare. It combines advanced ML techniques with a user-
friendly design to deliver a solution that improves diagnostic outcomes, reduces operational
burdens, and supports the broader goals of modern healthcare systems. This project underscores
the potential of AI-driven tools in revolutionizing the field of medical diagnostics, setting a
foundation for future innovations in cardiac care.

BE VII SEM [Link] CSE , RLJIT 3 2025-2026


CHAPTER 2

LITERATURE REVIEW AND PROPOSED SOLUTION

1. Detection of Cardiovascular Disease Using ECG Images in Machine Learning


and Deep Learning
Authors: Ms. K Jebima Jessy, Dr. G Manikandan, Ms. S. Hemalatha, Ms. Vilma Veronica

Summary

This study combines traditional ML models and advanced DL architectures, including


AlexNet and ResNet, to classify cardiovascular diseases from ECG images. It achieves a
remarkable accuracy of 99.79% using PhysioNet/CinC datasets, demonstrating the efficacy
of DL in disease detection. The work highlights the potential of DL for wearable health
monitoring systems.
Limitations

 Relies heavily on pre-trained networks, which can’t generalize well to new


datasets.
 Requires huge computational resources for training deep models like ResNet.

2. Early Diagnosis of Cardiac Diseases Using ECG Images and CNN-2D

Authors: Lerina Aversano, Mario Luca Bernardi, Marta Cimitile, Debora Montano, Riccardo
Pecori
Summary

By leveraging CNN-2D models and ECG images instead of traditional signal processing,
this study simplifies the preprocessing phase and reduces computational overhead.
The model achieves high accuracy in early detection and classification of arrhythmias.
It emphasizes efficient diagnosis with fewer resources.

BE VII SEM [Link] CSE , RLJIT 4 2025-2026


CNN-Based Arrhythmia Classification using ECG image Dataset Literature Survey
Limitations

 Focuses solely on image-based ECG data, potentially missing insights from


raw signal data.

 Model performance may degrade when applied to noisy or lower-


resolution images.

3. Prediction of Heart Disease Using Deep Convolutional Neural Networks

Authors: Awais Mehmood, Munwar Iqbal, Zahid Mehmood, Aun Irtaza, Marriam
Nawaz, Tahira Nazir, Momina Masood
Summary

This research uses CNNs to analyze health parameters, including ECG data, for heart
disease classification. The multi-layer CNN architecture extracts features and
categorizes patients as healthy or diseased. The study demonstrates CNN's ability to
improve diagnosis accuracy for heart disease.
Limitations

 Requires structured datasets with complete health parameters, which can’t


always be available.
 Lacks real-world testing on noisy or incomplete patient records.

4. ECG Heartbeat Classification Using CNN

Authors: Mayank Chourasia, Anurag Thakur, Shresth Gupta, Anurag Singh

Summary

This study employs a 1D-CNN to classify arrhythmias from ECG signals,


addressing challenges like noise and randomness. The model achieves
99% accuracy using the MIT- BIH dataset, automated and efficient
arrhythmia diagnosis.

BE VII SEM [Link] CSE , RLJIT 5 2025-2026


CNN-Based Arrhythmia Classification using ECG image Dataset Literature Survey
Limitations

 Uses only the MIT-BIH dataset, which can’t capture broader


demographic variations.

 The 1D-CNN approach might struggle with more complex ECG patterns
requiring higher-dimensional analysis.

5. CNN-Based Detection of Cardiovascular Diseases from ECG Images

Authors: Irem Sayin, Rana Gursoy, Buse Cicek, Yunus Emre Mert, Faith Ozturk, Taha Emre
Pamukcu, Ceylin Deniz Sevimli, Huseyin Uvet
Summary

Using the InceptionV3 model with transfer learning, this study classifies heart conditions
like myocardial infarction from ECG images with 93.27% accuracy. It highlights the
potential of CNNs in early detection and clinical decision- making for cardiac diseases.
Limitations

 Limited by the small dataset size (from a single cardiology institute), reducing
generalizability.
 Transfer learning methods may not adapt perfectly to new ECG image
datasets.

6. ECG Heartbeat Classification: A Deep Transferable


Representation Authors: Mohammad Kachuee, Shayan Fazeli, Majid
Sarrafzadeh Summary
This research classifies arrhythmias using deep CNNs following the AAMI EC57
standard and demonstrates transferable feature representations. The method effectively
classifies arrhythmias and supports related tasks like myocardial infarction detection.

BE VII SEM [Link] CSE , RLJIT 6 2025-2026


CNN-Based Arrhythmia Classification using ECG image Dataset Literature Survey

Limitations

 Transferability of features can vary across different arrhythmia types or datasets.

 Requires extensive labeled data to fine-tune representations for specific tasks.

7. Deep Learning Technique for Congenital Heart Disease Detection Using Stacking-
Based CNN-LSTM Models from Fetal Echocardiogram: A Pilot Study
Authors: Tawsifur Rahman, Mahmoud Katib A.A. Al-Ruwedi, MD. Shaheenur Islam Sumon,
Reema Yousef Kamal, Muhammad E.H. Chowdhry, Huseyin C. Yalcin Summary

This pilot study combines CNN and LSTM to analyze fetal echocardiogram videos to
detect congenital heart defects (CHDs), focusing on hypoplastic left heart syndrome
(HLHS). It demonstrates a chance for early prenatal diagnosis of CHDs to reduce infant
mortality.

Limitations

 Focuses only on fetal echocardiograms, limiting its application to adult


cardiac diagnosis.
 The study is a pilot and can lack statistical power due to small sample size.

8. Automated Detection of Coronary Artery Disease, Myocardial Infarction, and


Congestive Heart Failure Using Gabor CNN Model with ECG Signals
Authors: V Jahmunah, E.Y.K. Ng, Tan Ru San, U Rajendra Acharya

Summary

The study employs a GaborCNN model that integrates CNN with Gabor filters to
improve efficiency and accuracy in detecting various cardiovascular diseases. This
approach reduces computational complexity and enhances

BE VII SEM [Link] CSE , RLJIT 7 2025-2026


CNN-Based Arrhythmia Classification using ECG image Dataset Literature Survey

performance in diagnosing CVDs using ECG signals.


Limitations

 Custom Gabor filters can’t generalize well to diverse datasets or conditions.

 The approach might struggle with real-time deployment due to


computational overhead.

9. Deep Convolutional Neural Network for the Automated Diagnosis of


Congestive Heart Failure Using ECG Signals
Authors: U Rajendra Acharya, Hamido Fujita, Shu Lih Oh, Yuki Hagiwara

Summary

This work introduces an 11-layer CNN for diagnosing congestive heart failure (CHF)
from raw ECG signals, achieving 98.97% accuracy. The model minimizes preprocessing
and enhances CHF detection efficiency with high sensitivity and specificity.
Limitations

 Over-reliance on raw ECG data might make the model sensitive to noise or
signal artifacts.

 The study lacks exploration of cross-population validation.

10. Automatic ECG Diagnosis Using Convolutional Neural


Network Authors: Roberta Avanzato, Francesco Beritelli
Summary

This study automates ECG classification using CNNs, achieving over 98% sensitivity
and specificity. It classifies beats into categories like normal, atrial premature, and
ventricular contractions with high accuracy, streamlining cardiovascular anomaly
detection.

BE VII SEM [Link] CSE , RLJIT 8 2025-2026


CNN-Based Arrhythmia Classification using ECG image Dataset Literature Survey

Limitations

 Dataset size and variety might limit generalization to other populations or ECG
machines.
 High accuracy might not translate well to noisy or incomplete ECG data in real-
world settings.

Proposed Solution
The proposed solution for the project is an automated, scalable, and user-friendly platform that
has Convolutional Neural Networks (CNNs) to diagnose cardiac arrhythmias from ECG image
datasets. The system addresses the limitations of manual diagnostics by processing raw ECG
signals, converting them into image representations, and classifying them into multiple
arrhythmia categories with high accuracy. It also has modules for data acquisition,
preprocessing, model training, and validation, ensuring robust and reliable performance. The
platform features role-based access for administrators, healthcare professionals, and patients,
offering secure data storage, real-time monitoring, and remote accessibility via cloud
infrastructure. Designed to minimize errors and optimize resource utilization, the system
integrates seamlessly with hospital information systems and electronic medical records, enabling
efficient patient management and reducing operational burdens. Future enhancements include
incorporating wearable devices for real-time ECG monitoring and extending capabilities to
diagnose other cardiovascular conditions. This innovative solution aims to improve diagnostic
accuracy, streamline clinical workflows, and enhance patient outcomes in a cost-effective
manner.

BE VII SEM [Link] CSE , RLJIT 9 2025-2026


CHAPTER 3

REQUIREMENTS SPECIFICATION

Requirements specification is a specification of software requirements and hardware


requirements required to do the project.

3.1 Hardware Requirements Specification

Hardware Requirements are the hardware resources that are need to do the project work. These
resources are a computer resource provides functions and services to do the project. Hardware
resources required for the project are shown below.

● Processor : Intel Core i5 or above

● RAM : >=8GB

● Hard disk : Minimum 10 GB

● Device: Smartphone with Android version above 7.0

3.2 Software Requirements Specification

Software Requirements are the software resources that are need to do the project work. These
resources are installed on a computer in order to provide functions, services, hardware accessing
capabilities to do the project.

In our project we used the following software resources.

1. Operating System - Windows 10

BE VII SEM [Link] CSE , RLJIT 10 2025-2026


CNN-Based Arrhythmia Classification using ECG image Dataset Requirements specification

2. Programming Language and Frameworks


 Backend - Python

 Frontend - HTML, CSS, Javascript

 Framework – Tensorflow

3. Tools and Libraries


 Data preprocessing - OpenCV

 Model Optimization and Development – Tensorflow

4. Development Environment – Visual Studio Code

3.3 FUNCTIONAL REQUIREMENTS

1. Data Management

1.1 Input Data


 Accept ECG images (e.g., PNG, JPEG formats) as input for classification.

 Support bulk upload of ECG images for batch processing.

1.2 Data Preprocessing


 Convert input images to a uniform size for compatibility with the CNN model.

 Normalize pixel values for efficient model training and inference.

 Optionally, augment data (e.g., rotation, flipping, scaling) to improve


model robustness.

1.3 Dataset Management


 Allow users to organize and label datasets (e.g., normal, arrhythmia types).

BE VII SEM [Link] CSE , RLJIT 11 2025-2026


CNN-Based Arrhythmia Classification using ECG image Dataset Requirements specification

2. Model Development

2.1 Model Architecture


 Implement the Convolutional Neural Network (CNN) architecture optimized
for image classification tasks.
 Support customization of layers, including convolutional, pooling, and fully
connected layers.

2.2 Training
 Train the CNN model on labeled ECG image data.

 Incorporate early stopping to prevent overfitting.

 Log training metrics (accuracy, loss, precision, recall, F1-score).

2.3 Validation
 Validate the model using a separate validation dataset.

 Support cross-validation for reliable performance evaluation.

3. Classification
3.1 Prediction
 Classify ECG images into predefined categories (e.g.,normal, atrial
fibrillation, ventricular tachycardia ).

 Provide confidence scores (probabilities) for each classification.


3.2 Batch Processing
 Enable processing of multiple ECG images simultaneously.
3.3 Performance Matrics
Generate and display metrics such as accuracy, precision, recall,
confusion matrix, and ROC curves.

BE VII SEM [Link] CSE , RLJIT 12 2025-2026


CNN-Based Arrhythmia Classification using ECG image Dataset Requirements specification

4. User Interface

4.1 Upload Interface


 Provide a web-based or desktop interface for uploading ECG images.

4.2 Results Display


 Display classification results, including the class label and confidence score.

 Visualize ECG images alongside predictions.

4.3 Reporting
 Allow users to download detailed classification reports in PDF or Excel format.

5. Integration and Deployment

5.1 Integration
 Support API endpoints for integration with other healthcare systems.

5.2 Deployment
 Provide options for local deployment or cloud-based services for scalability.

6. Security and Compliance

6.1 Data Privacy


 Ensure compliance with regulations like HIPAA or GDPR for sensitive
healthcare data.

6.2 Access Control


 Allow role-based access control for secure usage of the system.

7. Error Handling
7.1 Invalid Input

BE VII SEM [Link] CSE , RLJIT 13 2025-2026


CNN-Based Arrhythmia Classification using ECG image Dataset Requirements specification
 Notify users of invalid file formats or corrupted ECG images.

7.2 Model Uncertainty

 Flag classifications with low confidence scores for manual review.

3.4 NON-FUNCTIONAL REQUIREMENTS

1) Performance
 The system should process and classify an uploaded ECG image within
3-5 seconds.

 The model must maintain a high level of accuracy, ideally above 95%, in
predicting arrhythmia types.

2) Scalability
 The application should be capable of handling simultaneous uploads from
multiple users without performance degradation.
 The system should support integration with more complex models or
additional arrhythmia types in the future.

3) Availability
 The system must have a 99.9% uptime to ensure it is accessible to users at
all times.
 It must automatically recover from failures or restarts without data loss.

4) Reliability
 The application should ensure accurate predictions, consistent
performance, and minimal downtime during usage.
 The uploaded files should always be processed without corruption or loss.

BE VII SEM [Link] CSE , RLJIT 14 2025-2026


CNN-Based Arrhythmia Classification using ECG image Dataset Requirements specification

5) Usability
 The interface must be intuitive and user-friendly for individuals with minimal
technical expertise.
 Feedback such as the prediction result and uploaded image display should be clear
and informative.

6) Security
 All uploaded ECG images must be securely stored to prevent unauthorized access.

 Sensitive data, such as patient information, must be handled in


compliance with the relevant data privacy regulations.

7) Maintainability
 The system should be designed in a modular way to facilitate easy updates,
such as replacing the model or modifying the user interface.
 Logs should be maintained to track errors and facilitate debugging.

8) Portability
 The system must be deployable across various platforms (e.g., local
machines, cloud servers) with minimal configuration.
 It should support deployment on OS like Windows, Linux, or

MacOS.

9) Efficiency
 The application should utilize computational resources effectively,
leveraging GPU acceleration for model inference when available.
 The image preprocessing and model prediction should minimize memory and
CPU usage.

BE VII SEM [Link] CSE , RLJIT 15 2025-2026


CHAPTER 4

SYSTEM DESIGN

4.1 Data Flow Diagram

Fig 1. Data Flow Diagram

1. Input: ECG Image


 The system starts by receiving an ECG image as input, representing the
rhythmic activity of the heart.

2. Image Pre-processing
 The input ECG image undergoes pre-processing, which typically includes:

o Resizing the image to a standard dimension to ensure compatibility with the


CNN model.
o Normalization of pixel values to enhance the model's performance.

o Potential conversion to grayscale to reduce complexity.

3. Feature Extraction
 The pre-processed image is passed through a CNN model that extracts key
features: These features may include patterns in the ECG waveform,

BE VII SEM [Link] CSE , RLJIT 16 2025-2026


CNN-Based Arrhythmia Classification using ECG image Dataset System design

 such as the P wave, QRS complex, and T wave shapes, critical for
identifying arrhythmias.

4. Feature Selection
 From the extracted features, the system selects the most relevant ones.

o This step reduces noise and ensures the classification focuses on


medically significant features.
o The selection process enhances the classification accuracy by
ignoring irrelevant information.

5. Image Classification
 Using the selected features, the CNN model classifies the input into one of
several categories
o Flutter: Rapid, irregular heartbeats.

o Abnormal: General abnormalities in the ECG waveform.

o Normal: Regular sinus rhythm.

o Q Waves: Specific waveform characteristics often linked to heart

damage.

o Sinus Arrest: A pause in the sinus node activity.

o Ventricular: Premature ventricular depolarization or other


ventricular abnormalities.

6. Output: Classification Results


 The results are displayed to the user in a categorized format. These
predictions help in diagnosing the heart condition based on the ECG pattern.

BE VII SEM [Link] CSE , RLJIT 17 2025-2026


CNN-Based Arrhythmia Classification using ECG image Dataset System design

4.2 Use case Diagram

Fig 2. Use case Diagram

1. User Input
 The user interacts with the system to optimize the classification model.

 The interaction may involve tasks such as fine-tuning hyperparameters, evaluating


model performance, or analyzing accuracy metrics.

2. Model Accuracy
 This block reflects the evaluation of the CNN model's performance in classifying
ECG images.
 Accuracy is a key metric which determines how well the model identifies arrhythmia
types such as Flutter, Normal Sinus Rhythm, or Ventricular Abnormalities.

3. Hyperparameters
 Hyperparameters are the adjustable settings of the CNN model that affect its
training process and performance.
 Examples include

BE VII SEM [Link] CSE , RLJIT 18 2025-2026


CNN-Based Arrhythmia Classification using ECG image Dataset System design

o Learning rate: Controls how much the model's weights are adjusted during
training.
o Batch size: Determines the count of samples processed before updating
the weights.
o Number of layers or filters: Defines the CNN architecture.

o Epochs: Number of training iterations.

4. Relationship Between Accuracy and Hyperparameters


 The diagram highlights the cyclic relationship between hyperparameters and
model accuracy
o The user adjusts hyperparameters based on model performance metrics.

o The model is retrained with updated hyperparameters, and accuracy


is re- evaluated.
 This process continues iteratively to achieve optimal model performance.

5. Goal
 The objective of the process is to fine-tune the model for the best classification
results, ensuring high accuracy and reliability in identifying arrhythmias.

4.3 Module Description

1. User Interaction
 The user uploads an ECG image through a web interface. This image represents the
electrical activity of the heart, and the goal of the system is to classify it into one of
several arrhythmia types or determine if it's normal.

BE VII SEM [Link] CSE , RLJIT 19 2025-2026


CNN-Based Arrhythmia Classification using ECG image Dataset System design

2. Preprocessing of the ECG Image

 Once the image is uploaded, it is processed in several ways to prepare it for analysis.
The image is first converted into grayscale (which simplifies it by removing color
information), then resized to a standard size that the model expects. The purpose of
preprocessing is to normalize and standardize the input for accurate classification.

3. Model Prediction
 The preprocessed image is then fed into a trained machine learning model (a
Convolutional Neural Network, or CNN). The CNN has been trained on many ECG
images, allowing it to recognize patterns and characteristics of the image that are
associated with different heart conditions.
 The model processes the image to extract relevant features, such as the shape and
timing of the heart’s electrical waves (P-wave, QRS complex, T- wave).

4. Classification
 Based on the extracted features, the model classifies the ECG image into one of
the predefined categories:
o Flutter Waves (a type of abnormal rhythm)

o Abnormal (irregular heart sounds)

o Normal Sinus Rhythm (healthy heart rhythm)

o Q Wave (sign of heart damage)

o Sinus Arrest (a pause in normal heart rhythm)

o Ventricular Premature Depolarization (irregular heartbeats


originating in the ventricles)

5. Displaying Results

BE VII SEM [Link] CSE , RLJIT 20 2025-2026


CNN-Based Arrhythmia Classification using ECG image Dataset System design

 The result of the classification (e.g., “Normal Sinus Rhythm” or “Flutter


Waves”) is displayed to the user with the image they uploaded.

BE VII SEM [Link] CSE , RLJIT 21 2025-2026


CHAPTER 5

IMPLEMENTATION

5.1 Tools and Technologies Used


1. Flask: Flask is a simple web framework of Python that allows developers to build
web applications quickly and easily.

2. Keras: Keras is a high level neural networks API written in Python, capable of
running on top of TensorFlow, Theano, or CNTK. It is used to simplify the process of
building and training DL models.

3. TensorFlow: TensorFlow is an open source ML framework developed by the Google.


It provides comprehensive ecosystem for building and deploying machine learning
models.

4. NumPy: NumPy is a significant package for scientific computing in Python. It


provides support for a wide range of mathematical functions.

5. OpenCV (cv2): OpenCV (Open Source Computer Vision Library) is an open-source


computer vision and machine learning software library. It provides tools for image
processing and computer vision tasks.

6. HTML/CSS (via Jinja2): HTML (HyperText Markup Language) and CSS


(Cascading Style Sheets) are standard technologies for creating web pages. Jinja2 is a
templating engine for Python that allows dynamic content generation in HTML.

7. Werkzeug: Werkzeug is a comprehensive WSGI (Web Server Gateway Interface)


web application library for Python. It is used by Flask for handling requests and
responses.

8. OS Module: The os module in Python provides a way to use operating system-


dependent functionality like reading or writing to the file system.

BE VII SEM [Link] CSE , RLJIT 22 2025-2026


CNN-Based Arrhythmia Classification using ECG image Dataset Implementation

5.2 Algorithms/Methodologies Used

Methodologies
9. Data Collection and Preprocessing
o ECG Image Collection: A diverse set of ECG images representing various heart
conditions (both normal and abnormal) is collected. These images serve as the
dataset for training and testing the ML model.
o Image Preprocessing: The collected ECG images undergo several preprocessing
steps to certify they are suitable for analysis by the model:
 Grayscale Conversion: Since color information is not crucial for
ECG analysis, images are converted to grayscale to simplify the input.
 Resizing: The images are resized to a consistent shape to ensure they fit
the model’s input requirements.
 Normalization: Pixel values are scaled (e.g., to a range between 0 and 1)
to make the learning process more stable and faster.
10. Model Training
o Convolutional Neural Networks (CNNs): CNNs are a class of deep learning
algorithms particularly well-suited for image analysis. In this system, a CNN is
trained on the large dataset of ECG images to recognize patterns of the heart’s
electrical signals that correspond to various arrhythmias.
o Supervised Learning: The training process involves using labeled ECG images
(where the type of arrhythmia is already known) to teach the model how to classify
new, unseen images.
o Feature Extraction: The CNN automatically learns to extract key features from the
ECG images (e.g., specific waveforms, intervals, etc.) that are analytical for
distinguishing between different arrhythmia types.
11. Prediction and Classification
o Inference: After training, the network is used to predict a class of an unseen ECG
image. The model applies its learned features to classify the image into one of
several arrhythmia types or as normal.
o Multi-Class Classification: The system categorizes the ECG images into
multiple classes, such as “Flutter Waves,” “Normal Sinus Rhythm,” “Sinus Arrest,”
and others. This is done through a softmax function that outputs a possibility
distribution over all possible classes.

BE VII SEM [Link] CSE , RLJIT 23 2025-2026


CNN-Based Arrhythmia Classification using ECG image Dataset Implementation

12. Post-Processing and Result Presentation


o Once the image is classified, the result is formatted and displayed to the user via a
web interface. The system also shows the uploaded ECG image alongside the
predicted arrhythmia type for easy interpretation by healthcare professionals.

Algorithms Used

1. Convolutional Neural Networks (CNN)

o CNNs are the backbone of the classification model. The core idea is to use multiple
layers of convolutions, pooling, and fully connected layers to learn features and
make predictions. CNNs excel at extracting spatial hierarchies from images, which
makes them highly legitimate for analyzing ECG waveforms in images.
o Convolutional Layer: Detects patterns such as edges, curves, or specific features
within ECG signals.
o Max Pooling Layer: Minimize the dimensionality of the image while keeping
important features, making the model more efficient and preventing overfitting.
o Fully Connected Layer: After the convolutions and pooling, it makes the final
decision on the class label (the type of arrhythmia).

2. Activation Functions

o ReLU (Rectified Linear Unit): A commonly used activation function in CNNs,


ReLU introduces non-linearity to the model, allowing it to learn tangled patterns in
the ECG data.
o Softmax Function: At the final layer of the CNN, the softmax function converts the
raw output values (logits) into a probability distribution across multiple classes,
enabling multi-class classification.

BE VII SEM [Link] CSE , RLJIT 24 2025-2026


CNN-Based Arrhythmia Classification using ECG image Dataset Implementation

3. Optimization Algorithm

o Adam Optimizer: A variation of gradient descent that adapts the learning rate
during training. Adam is broadly used due to its efficiency and capability to handle
sparse gradients, which helps the model converge quickly while minimizing the loss
function.

4. Loss Function

o Categorical Cross-Entropy Loss: Since the task is multi-class classification,


categorical cross-entropy is used to measure how well the predicted probability
distribution aligns with the true class labels.

5. Evaluation Metrics

o Accuracy: This is the primary metric used to evaluate the model’s performance. It
represents the percentage of correctly classified ECG images.
o Confusion Matrix: Helps in analyzing the true positives (TP), true negatives (TN),
false positives (FP), and false negatives (FN) for each class, allowing a deeper
grasping of the model's performance across different arrhythmia categories.

Model Evaluation and Fine-Tuning

 After training the model, it is evaluated on a test dataset that wasn’t seen during training.
Based on performance metrics (like accuracy), the model may undergo hyperparameter
tuning (adjusting parameters like the learning rate (LR), batch size (BS), number of layers
(N), etc.) to improve its performance.

Deployment
 The trained model is deployed as a web aid, where users can upload ECG images, and the
model will predict and classify the arrhythmia type in real time.

BE VII SEM [Link] CSE , RLJIT 25 2025-2026


CHAPTER 6
SYSTEM TESTING
6.1 Test Cases

System testing for the provided CNN-based arrhythmia classification using ECG
images, which uses Flask, machine learning (CNN model), and image processing,
involves verifying that the system functions correctly under various conditions. Here are
the key aspects of system testing that should be performed:

Test ID Test Type Objective Expected Result

TC01 Functional Verify image upload functionality Image uploads successfully and
redirects to the result page.

TC02 Functional Ensure preprocessing and model CNN model predicts the correct
prediction arrhythmia type.

TC03 Functional Verify classification result display Classification result is shown along
with the uploaded ECG image.

TC04 Functional Verify handling of System shows an error message for


invalid/unsupported files invalid or unsupported files.

TC05 Non-Functional Test performance under multiple System processes images within a few
(Performance) uploads seconds.

TC06 Non-Functional Evaluate stability under high load System remains stable; no crashes;
(Load) minor delays acceptable.

TC07 Non-Functional Check system security against System blocks malicious uploads and
(Security) malicious actions prevents unauthorized access.

BE VII SEM [Link] CSE , RLJIT 26 2025-2026


CNN-Based Arrhythmia Classification using ECG image Dataset System Testing

TC08 Usability Check UI usability and UI is user-friendly; all buttons, links, and
navigation forms work properly.

TC09 Compatibility Ensure the application works Application displays and functions correctly
correctly on different browsers on Chrome, Firefox, Safari, Edge, etc.

TC10 Compatibility Ensure proper functionality on Application is responsive; users can upload
mobile devices images and view results on
smartphones/tablets.

TC11 Regression Ensure core functions work after System continues to classify ECG images
code updates accurately and display correct results after
updates.

TC12 Integration Verify frontend–backend Frontend sends uploaded image to backend;


communication backend processes it and returns correct
classification.

BE VII SEM [Link] CSE , RLJIT 27 2025-2026


CNN-Based Arrhythmia Classification using ECG image Dataset System Testing

6.2 RESULTS AND DISCUSSIONS

Fig 3. Epoch training

This image summarizes the performance of model to classify heart rhythm


irregularities (arrhythmias) using ECG (electrocardiogram) images.

1. Purpose of Training
o The goal is to teach the model to recognize patterns in ECG images that
indicate specific types of arrhythmias.
2. Process
o The model learns by analyzing a set of ECG images along with their
corresponding labels (indicating the type of arrhythmia).
o Training is done in stages called "epochs," where the model repeatedly goes
through the data to improve its predictions.

BE VII SEM [Link] CSE , RLJIT 28 2025-2026


CNN-Based Arrhythmia Classification using ECG image Dataset System Testing

3. Metrics Shown

o Loss: This measures how far off the model's predictions are from the actual
labels. Lower values mean the model is making better predictions.
o Accuracy: This is the percentage of correct predictions. Higher accuracy means
the model is identifying arrhythmias more reliably.
o These metrics are strategized for both the training data (data the model sees) and
validation data (data the model hasn’t seen, used to test its generalization).

4. Observation
o At the start (Epoch 1), the model has moderate accuracy and makes some
mistakes, but it's improving rapidly.

o By the final stage (Epoch 5), the model is highly accurate for both the training
and validation data, indicating it has learned well without overfitting
(memorizing the training data instead of generalizing).
5. Conclusion
o The model performs very well, showing over 100% accuracy in identifying
arrhythmias from unseen data. This suggests it could be effective in analyzing
ECG images for real-world applications like assisting in medical diagnoses.

Type of Set Accuracy


Training Set 100.0 %
Validation Set 100.0 %
Table 1. Accuracy

BE VII SEM [Link] CSE , RLJIT 29 2025-2026


CNN-Based Arrhythmia Classification using ECG image Dataset System Testing

Fig 4. Confusion Matrix

1. High Correct Classification


o Most of the predictions lie on the diagonal, which indicates a high accuracy for the model.

o For example:
 Class 0: 66 samples were correctly classified.
 Class 2: 101 samples were correctly classified.
 Class 3: 96 samples were correctly classified.

2. Misclassifications
o There are a few misclassified samples, as seen in the off-diagonal cells:
 For Class 0, the model misclassified 3 samples as Class 5.
 For Class 4, 9 samples were misclassified as Class 5.
 For Class 5, 2 samples were misclassified as Class 4.
3. Class-Specific Performance
o The model functions exceptionally well for most classes, with only minor errors.
o Classes 1, 2, and 3 show no misclassification (perfect performance on these labels).
o Misclassification occurs mainly between neighboring classes (e.g., Class 4 and
Class 5), possibly due to similarities in their ECG patterns.

BE VII SEM [Link] CSE , RLJIT 30 2025-2026


CNN-Based Arrhythmia Classification using ECG image Dataset System Testing

Implications

 The CNN-based model demonstrates strong classification ability, especially for certain classes
of arrhythmias, as indicated by the high values on the diagonal.
 The small number of misclassifications suggests that while the model is highly effective,
additional fine-tuning or larger datasets might help further reduce errors, particularly for similar-
looking classes.

This confusion matrix showcases the reliability of the CNN in distinguishing different
arrhythmia types from ECG images, with minimal errors. It provides a valuable diagnostic tool
to support healthcare professionals in analyzing ECG data.

BE VII SEM [Link] CSE , RLJIT 31 2025-2026


CHAPTER 7

CONCLUSION AND FUTURE SCOPE

Conclusion

The CNN-Based Arrhythmia Classification System aims to transforms the way arrhythmias are
diagnosed by leveraging deep learning techniques and ECG data. The system automates the
traditionally manual and labor-intensive process of diagnosing heart arrhythmias, offering faster,
more accurate results. With its ability to process ECG images and classify various arrhythmias,
the system not only amplifies diagnostic accuracy but also helps reduce human errors.
Furthermore, the user-friendly interface and secure data management make it an ideal tool for
healthcare professionals, administrators, and patients. The system is integrated with hospital
information systems ensures a seamless workflow, improving both operational efficiency and
patient care.

Future Scope

The future scope of the CNN-Based Arrhythmia Classification System includes several avenues
for growth and enhancement:

1. Incorporating Real-Time Monitoring: Integrating the system with wearable ECG


devices or real-time ECG monitoring platforms could enable continuous heart health
monitoring, providing timely alerts to healthcare professionals.

BE VII SEM [Link] CSE , RLJIT 32 2025-2026


CNN-Based Arrhythmia Classification using ECG image Dataset Conclusion

2. Explainable AI for Better Decision-Making: Incorporating explainable AI techniques


would bestow healthcare professionals with a deeper understanding of the model's
decision-making process, allowing for more transparent and reliable diagnoses.

3. Integration with Other Healthcare Systems: The system could be further integrated
with hospital management systems, Electronic Health Records (EHR), and telemedicine
platforms, enabling more holistic patient management and better cross-department
collaboration.

4. Data Privacy and Ethical AI: As the system evolves, continuous work on ensuring the
privacy of sensitive patient data, adhering to legal standards, and mitigating biases in AI
models will be crucial to maintaining trust and compliance with regulations like HIPAA
and GDPR.

5. Cloud-Based AI Model Updates: The use of cloud infrastructure could allow for
continuous updates to the AI model, ensuring that it stays up-to-date with new research
and improved algorithms, thus enhancing its diagnostic capabilities over time.

By pursuing these future developments, the system could further contribute to revolutionizing
cardiovascular health management, making it more efficient, accessible, and reliable.

BE VII SEM [Link] CSE , RLJIT 33 2025-2026


Appendices
CNN-Based Arrhythmia Classification using ECG image Dataset

APPENDICES

1. SAMPLE CODE
MODEL CODE ([Link])
import os
from flask import Flask, request, render_template, jsonify, redirect, url_for
from [Link] import secure_filename
from PIL import Image
import torch
from torchvision import transforms
from flask_cors import CORS

UPLOAD_FOLDER = "uploads"
ALLOWED_EXTENSIONS = {"png", "jpg", "jpeg"}
IMAGE_SIZE = 256
import json

# Hardcoded class names


class_names = ["F", "M", "N", "Q", "S", "V"]

app = Flask( name )


CORS(app)
[Link]["UPLOAD_FOLDER"] = UPLOAD_FOLDER
[Link](UPLOAD_FOLDER, exist_ok=True)

device = [Link]("cuda" if [Link].is_available() else "cpu")

class ArrhythmiaCNN([Link]):

BE VII SEM [Link] CSE , RLJIT 34 2025-2026


Appendices
CNN-Based Arrhythmia Classification using ECG image Dataset

def init (self, num_classes=3):


super(ArrhythmiaCNN, self). init ()
self.conv1 = [Link].Conv2d(3, 64, 3, padding=1)
[Link] = [Link].MaxPool2d(2, 2)
self.conv2 = [Link].Conv2d(64, 128, 3, padding=1)
self.fc1 = [Link](128 * (IMAGE_SIZE // 4) * (IMAGE_SIZE // 4), 512)
self.fc2 = [Link](512, num_classes)
def forward(self, x):
x = [Link]([Link](self.conv1(x)))
x = [Link]([Link](self.conv2(x)))
x = [Link]([Link](0), -1)
x = [Link](self.fc1(x))
return self.fc2(x)

model = None
model_loaded = False
model_path = [Link]("ARRHYTHMIA_CNN_PATH", "arrhythmia_cnn.pth")

def load_model():
global model, model_loaded
if model is None:
model = ArrhythmiaCNN(num_classes=len(class_names)).to(device)
if not model_loaded and [Link](model_path):
try:
model.load_state_dict([Link](model_path, map_location=device))
[Link]()
model_loaded = True
print(f"Loaded model from {model_path}")

BE VII SEM [Link] CSE , RLJIT 35 2025-2026


Appendices
CNN-Based Arrhythmia Classification using ECG image Dataset

except Exception as e:
print(f"Error loading the model: {e}")
model_loaded = False
return model_loaded

transform = [Link]([
[Link]((IMAGE_SIZE, IMAGE_SIZE)),
[Link](),
[Link](mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])

def allowed_file(filename):
return "." in filename and [Link](".", 1)[1].lower() in
ALLOWED_EXTENSIONS

@[Link]("/")
def homepage():
return render_template("[Link]")

@[Link]("/upload")
def upload():
return render_template("[Link]")

@[Link]("/predict", methods=["POST"])
def predict():
if not load_model():
return jsonify({"error": "Model is not loaded. Please train the model or provide
the model file."}), 500
if "file" not in [Link]:
BE VII SEM [Link] CSE , RLJIT 36 2025-2026
Appendices
CNN-Based Arrhythmia Classification using ECG image Dataset

return jsonify({"error": "No file uploaded"}), 400


file = [Link]["file"]
if [Link] == "":
return jsonify({"error": "No file selected"}), 400
if file and allowed_file([Link]):
filename = secure_filename([Link])
filepath = [Link]([Link]["UPLOAD_FOLDER"], filename)
[Link](filepath)
image = [Link](filepath).convert("RGB")
input_tensor = transform(image).unsqueeze(0).to(device)
with torch.no_grad():
output = model(input_tensor)
pred_label = [Link](output, dim=1).item()
[Link](filepath)
return jsonify({"prediction": class_names[pred_label]})
else:
return jsonify({"error": "Invalid file type"}), 400

if name == " main ":


# Change port to 5000 to avoid common permission issues
[Link](host="[Link]", port=5000, debug=True)

BE VII SEM [Link] CSE , RLJIT 37 2025-2026


Appendices
CNN-Based Arrhythmia Classification using ECG image Dataset

[Link]
import argparse
import json
import torch
import [Link] as nn
import [Link] as optim
from torchvision import datasets, transforms
from [Link] import DataLoader
from tqdm import tqdm

import os

# Constants
IMAGE_SIZE = 256
BATCH_SIZE = 32
EPOCHS = 50
LEARNING_RATE = 0.001

parser = [Link](description="Train arrhythmia CNN")


parser.add_argument("--data_dir", type=str, default=None, help="Path to data
directory (overrides automatic selection)")
parser.add_argument("--epochs", type=int, default=EPOCHS)
parser.add_argument("--batch_size", type=int, default=BATCH_SIZE)
parser.add_argument("--save_path", type=str, default="arrhythmia_cnn.pth")
args = parser.parse_args()

# Prefer `uploads/` if it contains class subfolders, otherwise use `dataset/`.


preferred_dirs = []
if args.data_dir:

BE VII SEM [Link] CSE , RLJIT 38 2025-2026


Appendices
CNN-Based Arrhythmia Classification using ECG image Dataset

preferred_dirs.append(args.data_dir)
preferred_dirs.extend(["uploads", "dataset"])

data_dir = None
for d in preferred_dirs:
if d and [Link](d):
# Check it contains at least one subdirectory (class folder)
entries = [name for name in [Link](d) if [Link]([Link](d, name))]
if len(entries) > 0:
data_dir = d
break

if data_dir is None:
raise SystemExit("No suitable data directory found. Create `uploads/<class_name>/...`
or `dataset/<class_name>/...`")

class_names = sorted([folder for folder in [Link](data_dir) if


[Link]([Link](data_dir, folder))])
NUM_CLASSES = len(class_names)
print(f"Using data directory: {data_dir} with classes: {class_names}")

# Transformations
transform = [Link]([
[Link]((IMAGE_SIZE, IMAGE_SIZE)),
[Link](),
[Link](mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])

# Load Dataset
full_dataset = [Link](root=data_dir, transform=transform)

BE VII SEM [Link] CSE , RLJIT 39 2025-2026


CNN-Based Arrhythmia Classification using ECG image Dataset Appendices

# Split Dataset 80% train, 20% val


train_size = int(0.8 * len(full_dataset))
val_size = len(full_dataset) - train_size
train_dataset, val_dataset = [Link].random_split(full_dataset, [train_size,
val_size])

train_loader = DataLoader(train_dataset, batch_size=args.batch_size, shuffle=True)


val_loader = DataLoader(val_dataset, batch_size=args.batch_size, shuffle=False)

# CNN Model
class ArrhythmiaCNN([Link]):
def init (self, num_classes=NUM_CLASSES):
super(ArrhythmiaCNN, self). init ()
self.conv1 = nn.Conv2d(3, 64, 3, padding=1)
[Link] = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(64, 128, 3, padding=1)
self.fc1 = [Link](128 * (IMAGE_SIZE // 4) * (IMAGE_SIZE // 4), 512)
self.fc2 = [Link](512, num_classes)

def forward(self, x):


x = [Link]([Link](self.conv1(x)))
x = [Link]([Link](self.conv2(x)))
x = [Link]([Link](0), -1)
x = [Link](self.fc1(x))
return self.fc2(x)

# Setup
device = [Link]("cuda" if [Link].is_available() else "cpu")
model = ArrhythmiaCNN().to(device)
BE VII SEM [Link] CSE , RLJIT 40 2025-2026
CNN-Based Arrhythmia Classification using ECG image Dataset Appendices

criterion = [Link]()
optimizer = [Link]([Link](), lr=LEARNING_RATE)

# Lists to store metrics for plotting


train_losses = []
val_losses = []
val_accuracies = []

# Training loop
for epoch in tqdm(range([Link]), desc="Training Epochs"):
[Link]()
running_loss = 0.0
for images, labels in tqdm(train_loader, desc=f"Epoch {epoch+1}/{[Link]}",
leave=False):
images, labels = [Link](device), [Link](device)
optimizer.zero_grad()
outputs = model(images)
loss = criterion(outputs, labels)
[Link]()
[Link]()
running_loss += [Link]()
avg_loss = running_loss / len(train_loader) if len(train_loader) > 0 else 0.0

# Validation
[Link]()
val_running_loss = 0.0
correct = 0
total = 0
with torch.no_grad():
for images, labels in val_loader:
BE VII SEM [Link] CSE , RLJIT 41 2025-2026
CNN-Based Arrhythmia Classification using ECG image Dataset Appendices

images, labels = [Link](device), [Link](device)


outputs = model(images)
loss = criterion(outputs, labels)
val_running_loss += [Link]()
_, predicted = [Link]([Link], 1)
total += [Link](0)
correct += (predicted == labels).sum().item()
val_avg_loss = val_running_loss / len(val_loader) if len(val_loader) > 0 else 0.0
val_accuracy = 100 * correct / total if total > 0 else 0.0

print(f"Epoch {epoch+1}/{[Link]}, Train Loss: {avg_loss:.4f}, Val Loss:


{val_avg_loss:.4f}, Val Acc: {val_accuracy:.2f}%")

# Append to lists
train_losses.append(avg_loss)
val_losses.append(val_avg_loss)
val_accuracies.append(val_accuracy)

[Link](model.state_dict(), args.save_path)
print(f"✅ Model saved as {args.save_path}")

# Save class name mapping for use by the web app


with open("class_names.json", "w") as f:
[Link](class_names, f)
print("✅ Saved class mapping to class_names.json")

# Plotting using matplotlib and saving as images


import [Link] as plt

BE VII SEM [Link] CSE , RLJIT 42 2025-2026


CNN-Based Arrhythmia Classification using ECG image Dataset Appendices

epochs = list(range(1, [Link] + 1))

# Plot Training and Validation Loss


[Link](figsize=(10, 5))
[Link](epochs, train_losses, label="Train Loss")
[Link](epochs, val_losses, label="Val Loss")
[Link]("Training and Validation Loss")
[Link]("Epoch")
[Link]("Loss")
[Link]()
[Link]("training_validation_loss.png")
[Link]()

# Plot Validation Accuracy


[Link](figsize=(10, 5))
[Link](epochs, val_accuracies, label="Val Accuracy")
[Link]("Validation Accuracy")
[Link]("Epoch")
[Link]("Accuracy (%)")
[Link]()
[Link]("validation_accuracy.png")
[Link]()

BE VII SEM [Link] CSE , RLJIT 43 2025-2026


CNN-Based Arrhythmia Classification using ECG image Dataset Appendices

SNAPSHOTS

Fig 5. Accuracy and Loss

Fig 6. User Interface

BE VII SEM [Link] CSE , RLJIT 44 2025-2026


Fig 7. Output

BE VII SEM [Link] CSE , RLJIT 45 2025-2026


REFERENCES
[1] PhysioNet MIT-BIH Arrhythmia Database Moody GB, Mark RG. The impact of the MIT- BIH
Arrhythmia Database. IEEE Eng in Med and Biol 20(3):45-50 (May-June 2001). (PMID: 11446209)

[2] Ms. K Jebima Jessy, Dr G Manikandan, Ms. S. Hemalatha, Ms. Vilma Veronica (2024). Detection of
Cardiovascular Disease Using ECG Images in Machine Learning and Deep Learning: Article. IJSRST.
[Link]/10.32628/IJSRST52411224

[3] Lerina Aversano, Mario Luca Bernardi, Marta Cimitile, Debora Montano, Riccardo Pecori (2023).
Early Diagnosis of Cardiac Diseases using ECG Images and CNN-2D: Conference KES. ScienceDirect.
Procedia Computer Science 225 (2023) 2866–2875.

[4] Awais Mehmood, Munwar Iqbal, Zahid Mehmood, Aun Irtaza, Marriam Nawaz, Tahira Nazir,
Momina Masood (2020). Prediction of Heart Disease Using Deep Convolutional Neural Networks:
Article. ResearchGate. [Link]/10.1007/s13369-020-05105-1

[5] Mayank Chourasia, Anurag Thakur, Shresth Gupta, Anurag Singh (2020). ECG Heartbeat
Classification Using CNN: Coneference UPCON. IEEE.
DOI:10.1109/UPCON50219.2020.9376451

[6] Irem Sayin, Rana Gursoy, Buse Cicek, Yunus Emre Mert, Faith Ozturk, Taha Emre Pamukcu, Ceylin
Deniz Sevimli, Huseyin Uvet (2024). CNN Based Detection of Cardiovascular Diseases from ECG
Images: arXiv. [Link]/10.48550/arXiv.2408.16800

[7] Mohammad Kachuee, Shayan Fazeli, Majid Sarrafzadeh (2018). ECG Heartbeat Classification: A
Deep Transferable Representation: arXiv:1805.00794v2

[8] Tawsifur Rahman, Mahmoud Katib A.A. Al-Ruwedi, MD. Shaheenur Islam Sumon, Reema Yousef
Kamal, Muhammad E.H. Chowdhry, Huseyin C. Yalcin (2023). Deep Learning Technique for Congenital
Heart Disease Detection Using Stacking-BasedCNN-LSTM Models From Fetal Echocardiogram: A Pilot
Study: Research Article. IEEEAccess. 10.1109/ACCESS.2023.3316719

[9] V Jahmunah, E.Y.K. Ng, Tan Ru San, U Rajendra Acharya (2021).Automated detection of coronary
artery disease, myocardial infarction and congestive heart failure using GaborCNN

BE VII SEM [Link] CSE , RLJIT 46 2025-2026


model with ECG signals: PubMed. 10.1016/[Link].2021.104457

[10] U Rajendra Acharya, Hamido Fujita, Shu Lih Oh, Yuki Hagiwara (2019). Deep Convolutional
Neural Network for the Automated Diagnosis of Congestive Heart Failure Using ECG Signals:
ResearchGate.10.1007/s10489-018-1179-1

[11] Roberta Avanzato, Francesco Beritelli (2020). Automatic ECG Diagnosis Using Convolutional
Neural [Link]/10.3390/electronics9060951

BE VII SEM [Link] CSE , RLJIT 47 2025-2026

You might also like