1 Rl 22 Final Report
1 Rl 22 Final Report
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
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.
Examiner 1:
Examiner 2:
ACKNOWLEDGEMENT
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
1 INTODUCTION 1-3
3 REQUIREMENTS 10-15
SPECIFICATION
5 IMPLEMENTATION 22-25
8 CONCLUSION 35-36
9 REFERENCES 37-38
10 APPENDICES 37-50
II
LIST OF FIGURES
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.
• 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.
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.
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
Summary
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.
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
Summary
The 1D-CNN approach might struggle with more complex ECG patterns
requiring higher-dimensional analysis.
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.
Limitations
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
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
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.
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.
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.
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.
● RAM : >=8GB
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.
Framework – Tensorflow
1. Data Management
2. Model Development
2.2 Training
Train the CNN model on labeled ECG image data.
2.3 Validation
Validate the model using a separate validation dataset.
3. Classification
3.1 Prediction
Classify ECG images into predefined categories (e.g.,normal, atrial
fibrillation, ventricular tachycardia ).
4. User Interface
4.3 Reporting
Allow users to download detailed classification reports in PDF or Excel format.
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.
7. Error Handling
7.1 Invalid Input
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.
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.
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.
SYSTEM DESIGN
2. Image Pre-processing
The input ECG image undergoes pre-processing, which typically includes:
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,
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.
5. Image Classification
Using the selected features, the CNN model classifies the input into one of
several categories
o Flutter: Rapid, irregular heartbeats.
damage.
1. User Input
The user interacts with the system to optimize the classification model.
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
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.
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.
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.
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)
5. Displaying Results
IMPLEMENTATION
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.
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.
Algorithms Used
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
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
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.
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.
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:
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.
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.
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.
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.
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.
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.
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.
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:
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.
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
class ArrhythmiaCNN([Link]):
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}")
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
[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
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>/...`")
# 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)
# 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)
# 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)
# 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
# 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}")
SNAPSHOTS
[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
[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