Confrom References Merged
Confrom References Merged
LEARNING TECHNIQUE
A PROJECT REPORT
Submitted by
ANANTHANAYAKI.S 822219104002
SANTHOSH.S 822219104033
SWATHIPRIYA.K 822219104037
of
BACHELOR OF ENGINEERING
IN
MAY 2023
I
ANNA UNIVERSITY: CHENNAI 600025
BONAFIDE CERTIFICATE
SIGNATURE SIGNATURE
Dr.K.L.NEELA,M.E., Ph.D., Mr.K.SATHEESHKUMAR,MCA., M.Phil.,
Assistant professor, Assistant professor,
HEAD OF THE DEPARTMENT, SUPERVISOR,
Department of CSE, Department of CSE,
University College of Engineering, University College of Engineering,
Thirukkuvalai-610204. Thirukkuvalai-610204.
II
ACKNOWLEDGEMENT
We express our deep sense of reverence and offer our thanks with profound
gratitude to our project guide Mr.K.SATHEESHKUMAR,MCA.,M.Phil, for
motivation and encourage infused in us. Hes readiness and eagerness for
consolation at all times, him educative inputs, concern and assistance have been
invaluable.
Finally we thank god almighty for his blessing without which we would have not
the project and made this project success.
III
ABSTRACT
Maintaining proper health and mental stability is critical for overall health and
well-being. Despite a good deal of research investment, sleep quality continues to
be a crucial public challenge. Nowadays, people of all age groups are affected by
improper sleep quality. Poor sleep can lead to a variety of neurological disorders.
Sleep disorders are common in all subsets of the population, independently of
gender. This public health challenge greatly affects quality of life in terms of both
physical and mental health. Insomnia, parasomnias, sleep-related breathing
difficulties, hypersomnia, bruxism, narcolepsy, and circadian rhythm disorders are
some common examples of sleep-related disorders. Some of these disorders can be
treated with proper analysis of early symptoms; in such cases, adequate sleep quality
is essential for the patient’s recovery. Artificial intelligence has several applications
in sleep medicine including sleep and respiratory event scoring in the sleep
laboratory, diagnosing and managing sleep disorders, and population health. While
still in its nascent stage, there are several challenges which preclude AI’s
generalizability and wide-reaching clinical applications. Artificial intelligence is a
powerful tool in healthcare that may improve patient care, enhance diagnostic
abilities, and augment the management of sleep disorders. However, there is a need
to regulate and standardize existing machine learning algorithms and deep learning
algorithm prior to its inclusion in the sleep clinic. In this project, we can develop the
framework for sleeping stage classification for both subjective data and ECG data
and classify the data using Convolutional neural network algorithm to analyse the
multiple sleeping stages.
IV
TABLE OF CONTENTS
ABSTRACT IV
LIST OF FIGURES VIII
LIST OF ABBREVIATION IX
1 INTRODUCTION 1
1.1 DEEP LEARNING 1
1.2 APPLICATIONS OF DEEP LEARNING 2
1.3 DEEP LEARNING WORKS 2
1.4 PREDICTIVE ANALYSIS 5
1.5 MACHINE LEARNING 7
1.6 ARTIFICIAL INTELLIGENCE 9
1.7 REINFORCEMENT LEARNING 11
2 LITERATURE REVIEW 14
2.1 DETECTION OF INSOMNIA USING ECG AND
EMG 14
2.2 AUTOMATIC IDENTIFICATION OF
INSOMNIA BASED ON SINGLE EEG 15
2.3 A SHORT TIME INSOMNIA 16
2.4 INSOMNIA TOWARD CONCEPT DRIFT
ROBUSTNESS 17
2.5 AUTOMATIC IDENTIFICATION OF
INSOMNIA USING OPTIMAL ANTISYMMETRIC 18
2.6 MULTITASK FMRI AND MACHINE
19
LEARNING APPROACH
2.7 DISCRIMINATING PARADOXICAL AND
20
PSYCHOPHSIOLOGIAL
V
3 SYSTEM ANALYSIS 21
3.1 EXISTING SYSTEM 21
3.1.1 DISADVANTAGES 22
3.2 PROPOSED SYSTEM 22
3.3 CONVOLUTIONAL NEURAL NETWORK 23
3.3.1 APPLICATION 24
25
3.3.2 ADVANTAGES
4 SYSTEM IMPLEMENTATION 26
4.1 DATASETS 26
4.2 HARDWARE REQUIRMENTS 28
4.3 SOFTWARE REQUIRMENTS 28
4.4 MODULES 28
4.4.1 DATASETS ACQUSITION 28
4.4.2 PREPROCESSING 29
4.4.3 FEATURS EXTRACTION 30
4.4.4 CLASSIFICATION 31
4.4.5 PREDICTION 32
5 SYSTEM DESIGN 33
5.1 SYSTEM ARCHITECTURE 33
5.2 UML DIAGRAMS 34
5.2.1 USE CASE DIAGRAM 34
5.2.2 CLASS DIAGRAM 35
5.2.3 ACTIVITY DIAGRAM 35
5.2.4 SEQUENCE DIAGRAM 36
5.2.5 COLLABORATION DIAGRAM 37
6 SYSTEM TESTING 39
6.1 SOFTWARE TESTING STRATEGIES 39
6.1.1 UNIT TESTING 39
6.1.2 FUNCTIONAL TESTING 40
6.1.3 ACCEPTANCE TESTING 40
VI
8 SNAPSHOTS 42
9 APPENDIX 53
11 REFERENCES 67
VII
LIST OF FIGURES
VIII
LIST OF ABBREVIATIONS
1 EEG ELECTROENCEPHALOGRAM
2 ECG ELECTROCARDIOGAPHY
3 EMG ELECTROMYOGRAPHY
IX
CHAPTER 1
INTRODUCTION
1
1.2 APPLICATIONS OF DEEP LEARNING
Deep learning applications are used in industries from automated driving to
medical devices.Automated Driving: Automotive researchers are using deep
learning to automatically detect objects such as stop signs and traffic lights. In
addition, deep learning is used to detect pedestrians, which helps decrease
accidents.
Aerospace and Defense: Deep learning is used to identify objects from satellites
that locate areas of interest, and identify safe or unsafe zones for troops.
Most deep learning methods use neural network architectures, which is why
deep learning models are often referred to as deep neural networks.
The term “deep” usually refers to the number of hidden layers in the neural
network. Traditional neural networks only contain 2-3 hidden layers, while deep
networks can have as many as 150.
2
Deep learning models are trained by using large sets of labeled data and neural
network architectures that learn features directly from the data without the need for
manual feature extraction.
One of the most popular types of deep neural networks is known as convolutional
neural networks (CNN or ConvNet). A CNN convolves learned features with
input data, and uses 2D convolutional layers, making this architecture well suited
to processing 2D data, such as images.
CNNs eliminate the need for manual feature extraction, so you do not need to
identify features used to classify images. The CNN works by extracting features
directly from images. The relevant features are not pretrained; they are learned
while the network trains on a collection of images. This automated feature
extraction makes deep learning models highly accurate for computer vision tasks
such as object classification.
3
Another key difference is deep learning algorithms scale with data, whereas
shallow learning converges. Shallow learning refers to machine learning methods
that plateau at a certain level of performance when you add more examples and
training data to the network.
A key advantage of deep learning networks is that they often continue to improve
as the size of your data increases.
The three most common ways people use deep learning to perform object
classification are:
To train a deep network from scratch, you gather a very large labeled data set
and design a network architecture that will learn the features and model. This is
good for new applications, or applications that will have a large number of output
categories. This is a less common approach because with the large amount of data
and rate of learning, these networks typically take days or weeks to train.
Transfer Learning
Most deep learning applications use the transfer learning approach, a process
that involves fine-tuning a pretrained model. You start with an existing network,
such as AlexNet or GoogLeNet, and feed in new data containing previously
unknown classes. After making some tweaks to the network, you can now perform
a new task, such as categorizing only dogs or cats instead of 1000 different objects.
This also has the advantage of needing much less data (processing thousands of
images, rather than millions), so computation time drops to minutes or hours.
4
Feature Extraction
Predictive analytics has received a lot of attention in recent years due to advances
in supporting technology, particularly in the areas of big data and machine learning.
Predictive analytics is often discussed in the context of big data, Engineering data,
for example, comes from sensors, instruments, and connected systems out in the
world. Business system data at a company might include transaction data, sales
results, customer complaints, and marketing information. Increasingly, businesses
make data-driven decisions based on this valuable trove of information. To extract
value from big data, businesses apply algorithms to large data sets using tools such
as Hadoop and Spark. The data sources might consist of transactional databases,
equipment log files, images, video, audio, sensor, or other types of data. Innovation
often comes from combining data from several sources.
With all this data, tools are necessary to extract insights and trends. Machine
learning techniques are used to find patterns in data and to build models that predict
future outcomes. A variety of machine learning algorithms are available, including
5
linear and nonlinear regression, neural networks, support vector machines, decision
trees, and other algorithms.
6
sounds and provides instant feedback via a smart phone app to help patients
manage asthma and COPD.
7
• Computational finance, for credit scoring and algorithmic trading
• Image processing and computer vision, for face recognition, motion
detection, and object detection
• Computational biology, for tumor detection, drug discovery, and DNA
sequencing
• Energy production, for price and load forecasting
• Automotive, aerospace, and manufacturing, for predictive maintenance
• Natural language processing, for voice recognition applications
Machine learning uses two types of techniques: supervised learning, which trains
a model on known input and output data so that it can predict future outputs,
and unsupervised learning, which finds hidden patterns or intrinsic structures in
input data.
Supervised Learning
Classification Techniques
8
for hand-writing recognition use classification to recognize letters and numbers. In
image processing and computer vision, unsupervised pattern
recognition techniques are used for object detection and image segmentation.
Regression Techniques
Use regression techniques if you are working with a data range or if the nature of
your response is a real number, such as temperature or the time until failure for a
piece of equipment.
Unsupervised Learning
Clustering
Taking raw data and making it useful for an accurate, efficient, and meaningful
model is a critical step. In fact, it represents most of your AI effort.
Data preparation requires domain expertise, such as experience in speech and audio
signals, navigation and sensor fusion, image and video processing, and radar and
lidar. Engineers in these fields are best suited to determine what the critical features
of the data are, which are unimportant, and what rare events to consider.
AI also involves prodigious amounts of data. Yet labeling data and images
is tedious and time-consuming. Sometimes, you don’t have enough data, especially
for safety-critical systems. Generating accurate synthetic data can improve your
data sets. In both cases, automation is critical to meeting deadlines.
Deployment
The deployment process is accelerated when you generate code from your models
and target your devices. Using code generation optimization techniques and
hardware-optimized libraries, you can tune the code to fit the low power profile
required by embedded and edge devices or the high-performance needs of
enterprise systems and the cloud.
10
1.7 REINFORCEMENT LEARNING
11
Deep learning spans all three types of machine learning; reinforcement learning
and deep learning are not mutually exclusive. Complex reinforcement learning
problems often rely on deep neural networks, a field known as deep reinforcement
learning
Deep neural networks trained with reinforcement learning can encode complex
behaviors. This allows an alternative approach to applications that are otherwise
intractable or more challenging to tackle with more traditional methods. For
example, in autonomous driving, a neural network can replace the driver and
decide how to turn the steering wheel by simultaneously looking at multiple
sensors such as camera frames and lidar measurements. Without neural networks,
the problem would normally be broken down in smaller pieces like extracting
features from camera frames, filtering the lidar measurements, fusing the sensor
outputs, and making “driving” decisions based on sensor inputs.
Robotics: Reinforcement learning can help with applications like robotic grasping,
such as teaching a robotic arm how to manipulate a variety of objects for pick-and-
12
place applications. Other robotics applications include human-robot and robot-
robot collaboration.
13
CHAPTER 2
LITERATURE SURVEY
14
2.2 TITLE: AUTOMATIC IDENTIFICATION OF INSOMNIA
BASED ON SINGLE-CHANNELEEG LABELLED WITH SLEEP
STAGE ANNOTATIONS
AUTHOR: BUFANG YANG YEAR 2020
15
2.3 TITLE: A SHORT-TIME INSOMNIA DETECTION SYSTEM
BASED ON SLEEP EOG WITH RCMSE ANALYSIS
AUTHOR: CHIH-EN KUO YEAR 2020
Sleep takes approximately one-third of human live. A good sleep can help us
getting the body to work right again, improved learning ability, physical
development, emotional regulation, and good quality of life in human physiology.
However, the prevalence of insomnia symptoms without restrictive criteria is
approximately 33% in the general population. In the United States of America, 50-
70 million people suffer from sleep disorders: among them, 30% of patients suffer
from insomnia and 10% from chronic insomnia. Insomnia is defined as chronic
when it has persisted for at least three months at a frequency of at least three times
per week. When the disorder meets the symptom criteria but has persisted for less
than three months, it is considered short-term insomnia. To diagnose insomnia, the
physician may first execute a physical exam to look for signs of medical problems
that may be related to insomnia and ask some sleep-related questions, such as
sleep-wake pattern and daytime sleepiness. In addition, the physician may ask a
subject to keep a sleep diary with the actigraphy for a couple of weeks. If the cause
of insomnia is not clear, the subject should spend one or two nights at a sleep centre
diagnosing another sleep disorder using polysomnography (PSG), such as sleep
apnea. PSG recordings, which including electroencephalogram (EEG),
electrooculogram (EOG), electromyogram (EMG), and other physiological signals
are usually obtained from patients and scored by a well-trained clinical staff.
Moreover, manual sleep scoring and diagnosis is a time consuming and subjective
process, and the conventional polysomnography which uses many wires to connect
instrument to patient is often a problem that leads to sleep disturbance.
16
2.4 TITLE: INSOMNIA: TOWARDS CONCEPT-DRIFT
ROBUSTNESS IN NETWORK INTRUSION DETECTION
AUTHOR: GIUSEPPINA ANDRESINI YEAR 2021
17
2.5 TITLE: AUTOMATIC IDENTIFICATION OF INSOMNIA
USING OPTIMAL ANTISYMMETRIC BIORTHOGONAL
WAVELET FILTER BANK WITH ECG SIGNALS
AUTHOR: MANISH SHARMA YEAR 2021
18
2.6 TITLE: MULTITASK FMRI AND MACHINE LEARNING
APPROACH IMPROVE PREDICTION OF DIFERENTIAL
BRAIN ACTIVITY PATTERN IN PATIENTS WITH INSOMNIA
DISORDER
AUTHOR: MI HYUN LEE YEAR 2021
19
2.7 TITLE: DISCRIMINATING PARADOXICAL AND
PSYCHOPHYSIOLOGICAL INSOMNIA BASED ON
STRUCTURAL AND FUNCTIONAL BRAIN IMAGES: A
PRELIMINARY MACHINE LEARNING STUDY
AUTHOR: MORTAZA AFSHANI YEAR 2022
Recent studies have suggested that there are various ID subtypes with different
ethology and distinct pathophysiology. Subtyping ID is an ongoing debate in sleep
medicine and has changed over different versions of the International
Classification of Sleep Disorders (ICSD). In ICSD-2, several ID subtypes were
introduced including paradoxical insomnia (PDI) and psychophysiological
insomnia (PPI). ICSD-2 defines PDI as subjective complaints of insomnia, while
polysomnography (PSG) shows near-normal sleep patterns, causing a discrepancy
between subjective and objective sleep measures. PPI, instead, is characterized by
increased arousal before or during sleep and learned-sleep preventing associations
in a routine bedroom setting. Put differently, the more a patient tries to sleep, the
more he/she gets anxious and more difficult to initiate sleep, which causes low
functional performance during wakefulness. Thereby, PPI is described by fear of
sleep and the bedroom environment. However, although ICSD-3 has emphasized
the existence of the ID subtypes, it proposed to consider it as a single category,
entitled chronic ID, as there are no customized therapeutic approaches for each
subtype. This preliminary study provides evidence that structural and functional
brain measures can help to distinguish two common subtypes of ID from each other
and from healthy subjects. Moreover, we observed that the multimodal brain
measure is a bit better than the unimodal brain measure to separate ID subtypes
20
CHAPTER 3
SYSTEM ANALYSIS
21
3.1.1 DISADVANTAGES
22
performance of the model. Once the data is pre-processed and split, the next step
is to design the CNN architecture. The architecture should be designed to learn
relevant features from the pre-processed data and classify the sleep stages
accurately. A common approach is to use 1D or 2D CNNs with multiple
convolutional layers and pooling layers. The output of the final layer is fed to a
fully connected layer and softmax activation to predict the sleep stage. And also
predict the sleeping disorder with new datasets, then provide the precaution details .
• Feature extraction;
• Feature mapping;
The weights in all layers of a CNN are learned through training. Also, the network
learns to extract its own features automatically
23
This diagram shows the multiple layers such as input layer, four hidden layers, and
an output layer. This network is designed to perform image processing. The input
layer consists of 28×28 sensor neurones, receives the images of different characters
that have been approximately centred and normalized in size. We can use the CNN
algorithm framework to classify multiple sleeping stages.
3.3.1 APPLICATIONS
Sleep stage classification has several applications in the field of sleep medicine and
research, including:
24
3.3.2 ADVANTAGES
25
CHAPTER 4
SYSTEM IMPLEMENTATION
4.1 DATASETS
26
problems. The proposed approach considers two different categories of sleep
recordings which include subjects’ effects with different types of sleep related
disorders and the other category is subject having complete healthy control. The
proposed work is divided into two phases, in the first phase identifying the suitable
features from the extracted feature vector through obtaining different selection
algorithms. In the second phase, an ensemble learning stacking model is considered
for the classification of the sleep stages
Deepest Sleep
Reduce muscle tension
Walk and talk in sleep
4.4 MODULES
4.4.1 DATASETS ACQUISITION
In this module we can input the CSV file about EEG data and also EDF file.
The Physionet dataset is a dataset of EEG recordings for multiple persons
PhysioNet is a public repository of biomedical signals and time series data, which
can be used for research and development in the field of sleep stage prediction. It
28
contains large datasets of sleep and physiological data, including EEG, ECG, and
respiration signals, which can be used to train and evaluate deep learning
algorithms for sleep stage prediction. In this module, we can input the CSV file and
EDF file. CSV file contains the frequency values. EDF (European Data Format) is
a common file format for storing physiological signals, including those recorded
during sleep. EDF files typically contain several signals, including EEG, EOG,
EMG, and ECG. These signals are recorded using electrodes placed on the scalp,
face, and body, and provide information about the electrical activity of the brain
and muscles during sleep. To use an EDF file for sleeping stage prediction, the first
step is to load the file into a software program or Python library that can read EDF
files. Examples of such libraries include MNE-Python and pyEDFlib. Once the
EDF file is loaded, the next step is to extract features from the signals that are
relevant to sleep stage prediction. Common features include the power spectrum,
the amplitude of specific frequency bands, and the correlation between different
signals.
4.4.2 PREPROCESSING
Preprocessing is an important step in the analysis of EEG data, as it helps to
remove artifacts and improve the quality of the data. In the pre-processing stage,
continuous EEG recordings are firstly segmented without overlapping by a sliding
time window. In this module, perform preprocessing steps to eliminate the
29
irrelevant and missing datasets from uploaded CSV file. The first step is to load
the EDF file into memory using a library such as MNE-Python or pyEDFlib. The
CSV file containing the sleep stage annotations can also be loaded into a Pandas
DataFrame. Sleep signals are often contaminated by noise and artifacts. Signal
filtering can be used to remove these unwanted components and improve the
quality of the signal. Common filtering techniques include bandpass filtering,
notch filtering, and high-pass filtering.
30
Based on features model file can be created using CNN algorithm for future
verification.
CNN model
Input: Structured
datasets Model
construction
Output: Model file
4.4.4 CLASSIFICATION:
The features are divided into training, validation, and test sets, and are
organized into a format that can be used as input to the CNN. A CNN is designed
and configured, including the choice of architecture, number of layers, and
activation functions. The CNN is trained on the training set, using a loss function
and an optimization algorithm. The model is validated on the validation set to
prevent overfitting and monitor the performance of the model. The trained CNN is
evaluated on the test set to assess its performance in classifying the sleep stages. A
CSV (Comma-Separated Values) file can be used for sleep stage classification in
EEG datasets by providing annotations for each epoch of data. An epoch is a fixed-
length segment of EEG data, typically 30 seconds in length. The annotations in the
CSV file indicate the sleep stage that each epoch belongs to, as determined by a
sleep expert. To classify EEG datasets using a CSV file, the first step is to load the
EEG data and the corresponding CSV file into memory. The EEG data can be
loaded using a library such as MNE-Python or pyEDFlib, while the CSV file can
be loaded into a Pandas DataFrame. Once the data is loaded, the next step is to
31
preprocess the EEG data to extract features that are relevant for sleep stage
classification. This can involve techniques such as filtering the data, resampling
the data, and extracting features such as power spectral density, amplitude of
specific frequency bands, and correlation between different EEG channels. A
common approach for EEG classification is to use a convolutional neural network
(CNN). The CNN is trained on the labeled epochs to learn the relationship between
the EEG features and the sleep stages. The performance of the CNN is evaluated
using metrics such as accuracy, precision, recall, and F1 score.
4.4.5 PREDICTION
Finally, the trained CNN can be used to classify the sleep stages in new EEG
datasets. The EEG data is divided into epochs, and the CNN predicts the sleep stage
for each epoch. This information can be used to analyze the sleep patterns of
individuals and can provide valuable insights for clinical and research purposes. In
this module, input the EEG readings in terms of numeric format. And match the
reading with CNN model file. Then classify the stages of sleeping disorders and
provide the precautions to users
32
CHAPTER 5
SYSTEM DESIGN
33
5.2 UML DIAGRAMS
Datasets Acquisiton
Preprocessing
Training_phase
Model building
Testing_phase
Prediction
34
5.2.2 CLASS DIAGRAM
35
Datasets acquisition
Preprocessing
Features extraction
Classification
36
Datasets Acquisition Preprocessing Features extraction Classification
Prediction
6 : Performance evaluation()
37
38
CHAPTER 6
SYSTEM TESTING
➢ Unit Testing
➢ Functional Testing
➢ Acceptance Testing
39
6.1.2 FUNCTIONAL TESTING
40
CHAPTER 7
In this study we can input the EEG datasets related to sleeping stages and
developed in Python framework. Accuracy as main criterion is considered for
evaluating and comparing the different classification methods. The performance of
the sleep stage classification is evaluated using repeated random sub-sampling
validation. To measure the classification accuracy, the overall accuracy value is
calculated as follows
ACCURACY (%)
72
70
68
66
64
62
60
58
56
54
SUPPORT VECTOR DEEP NEURAL NETWORK CONVOLUTIONAL NEURAL
MACHINE NETWORK
Fig 3: Accuracy
41
CHAPTER 8
SNAPSHOTS
DATASETS
42
X175 9200.0 -9.848587 69.550894 -570.0 -45.0 -9.0 27.0 1958.0
43
[179 rows x 8 columns]
44
45
46
47
Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
==========================================================
=======
conv1d (Conv1D) (None, 176, 256) 1024
dropout (Dropout) (None, 176, 256) 0
conv1d_1 (Conv1D) (None, 174, 128) 98432
dropout_1 (Dropout) (None, 174, 128) 0
48
1 0.63 0.69 0.66 459
2 0.74 0.40 0.52 450
3 0.89 0.79 0.84 457
4 0.71 0.88 0.79 469
micro avg 0.78 0.74 0.76 2300
macro avg 0.79 0.74 0.75 2300
weighted avg 0.79 0.74 0.75 2300
samples avg 0.74 0.74 0.74 2300
accuracy: 76.43%
49
50
51
Accuracy score: 0.6699909338168631
[155 0 0 2 0]
[ 96 5 4 1 3]
[ 78 12 443 21 8]
[ 0 0 5 100 0]
[ 84 27 23 0 36]]
precision recall f1-score support
Sleep stage W 0.38 0.99 0.54 157
Sleep stage 1 0.11 0.05 0.07 109
Sleep stage 2 0.93 0.79 0.85 562
Sleep stage 3/4 0.81 0.95 0.87 105
Sleep stage R 0.77 0.21 0.33 170
52
CHAPTER 9
APPENDIX
53
from plotly import tools
from plotly.offline import init_notebook_mode, iplot
import imblearn
init_notebook_mode(connected=True)
pd.set_option('display.max_columns', 100)
data = pd.read_csv('Data/Sleepdataset.csv')
data.head()
data.tail()
data.shape
data['y'].value_counts()
data.y.hist();
plt.figure(figsize=(50, 4))
plt.subplot(131)
[plt.plot(data.values[i][1:-1]) for i in range(23)];
dic = {5: 0, 4: 0, 3: 0, 2: 0, 1: 1}
data['y'] = data['y'].map(dic)
print(data['y'].value_counts())
data.head()
data = data.drop('Unnamed', axis=1)
data = shuffle(data)
data.describe()
data.info()
print('Number of records of Non sleep {0} VS sleep
{1}'.format(len(data[data['y'] == 0]),
len(data[data['y'] == 1])))
data[data['y'] == 0].describe().T
54
print(data[data['y'] == 0].describe().T)
data[data['y'] == 1].describe().T
print(data[data['y'] == 1].describe().T)
print('Totall Mean VALUE for sleep : {}'.format((data[data['y'] ==
1].describe().mean()).mean()))
print('Totall Std VALUE for sleep : {}'.format((data[data['y'] ==
1].describe().std()).std()))
range(2)];
[(plt.figure(figsize=(8, 4)), plt.title('Sleep'), plt.plot(data[data['y'];
def indic(data):
max = np.max(data, axis=1)
min = np.min(data, axis=1)
return max, min
x1, y1 = indic(Not_Schizophrenia)
x2, y2 = indic(Schizophrenia)
fig = plt.figure(figsize=(14, 6))
ax1 = fig.add_subplot(111)
ax1.scatter(x1, y1, s=10, c='b', label='Not Sleep')
ax1.scatter(x2, y2, s=10, c='r', label='Sleep')
plt.legend(loc='lower left');
plt.show()
# Just Epileptic
x, y = indic(data[data['y'] == 1].iloc[:, range(0, len(data.columns) - 1)]
plt.figure(figsize=(14, 4))
plt.title('Sleep')
plt.scatter(x, y, c='r');
plt.show()
55
x, y = indic(data[data['y'] == 0].iloc[:, range(0, len(data.columns) - 1)]
plt.figure(figsize=(14, 4))
plt.title('NOT Sleep')
plt.scatter(x, y);
plt.show()
# define oversampling strategy
# fit and apply the transform
X, y = oversample.fit_resample(data.drop('y', axis=1), data['y'])
X.shape, y.shape
print('Number of records of Non Sleep {0} VS Sleep {1}'.format(len(y == True),
normalized_df = pd.DataFrame(normalize(X))
normalized_df
normalized_df['y'] = y
print('Normalized Totall Mean VALUE for Sleep: {}'.format(
(normalized_df[normalized_df['y'] == 1].describe().mean()).mean()))
print( 'Normalized Totall Std VALUE for Sleep: {}'.format(
(normalized_df[normalized_df['y'] == 1].describe().std()).std()))
print('Normalized Totall Mean VALUE for NOT Sleep: {}'.format(
(normalized_df[normalized_df['y'] == 0].describe().mean()).mean()))
print('Normalized Totall Std VALUE for NOT Sleep: {}'.format(
(normalized_df[normalized_df['y'] == 0].describe().std()).std()))
def training():
data = pd.read_csv('Data/Sleepdataset.csv')
data.head()
from sklearn.preprocessing import LabelBinarizer
X = np.asarray(data.values)
56
X = np.asarray(X[:, 1:-1])
X = X.astype(float)
minm = X.min()
maxm = X.max()
X_norm = (X - minm) / (maxm - minm)
print(X.shape)
from sklearn.model_selection import train_test_split
mlb = LabelBinarizer()
y = np.asarray(data['y'])
# y=np.array.astype('float')
# Y=mlb.fit_transform(y)
Y = y.astype(float)
# X=X.reshape(1200,178,1)
# print(X.shape)
Y=Y-1
from tensorflow.python.keras.utils.np_utils import to_categorical
Y = to_categorical(Y)
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.20,)
model = Sequential()
model.add(Conv1D(filters=256, kernel_size=3, activation='relu')
model.add(Dropout(0.3))
model.add(Conv1D(filters=128, kernel_size=3, activation='relu'))
model.add(Dropout(0.3))
model.add(Conv1D(filters=128, kernel_size=3, activation='relu'))
model.add(Dropout(0.3))
model.add(Conv1D(filters=64, kernel_size=3, activation='relu'))
57
model.add(Dropout(0.3))
model.add(Conv1D(filters=32, kernel_size=3, activation='relu'))
model.add(Dropout(0.3))
model.add(MaxPooling1D(pool_size=2))
model.add(Flatten())
# model.add(Dense(32, activation='relu'))
model.add(Dense(5, activation='softmax'))
# model.compile(loss='categorical_crossentropy', optimizer='adam')
model.summary()
model.compile(optimizer='adam', loss='binary_crossentropy')
y_ints = [y.argmax() for y in Y_train]
from sklearn.utils import class_weight
class_weights = class_weight.compute_class_weight('balanced',np.unique(y_ints)
history2 = model.fit(X_train, Y_train, 100, 150, verbose=1)
# class_weight=class_weight_dict)
model.save('cnn.hdf5')
acc = history2.history['accuracy']
loss = history2.history['loss']
epochs = range(1, len(acc) + 1)
plt.plot(epochs, acc, 'b', label=' accurarcy')
plt.title('accurarcy')
plt.legend()
plt.show()
def eeeg():
import numpy as np
import matplotlib.pyplot as plt
58
import mne
from mne.datasets.sleep_physionet.age import fetch_data
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix
from sklearn.metrics import classification_report
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import FunctionTransformer
#import pandas as pd
#sleep_data = pd.read_csv('sleep.csv')
#sleep_data.info()
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne.datasets.sleep_physionet.age import fetch_data
# from mne.time_frequency import
ALICE, BOB = 0, 1
[alice_files, bob_files] = fetch_data(subjects=[ALICE, BOB], recording=[1])
mapping = {'EOG horizontal': 'eog',
'Resp oro-nasal': 'misc',
'EMG submental': 'misc',
'Temp rectal': 'misc',
'Event marker': 'misc'}
raw_train = mne.io.read_raw_edf(alice_files[0])
annot_train = mne.read_annotations(alice_files[1])
raw_train.set_annotations(annot_train, emit_warning=False)
59
raw_train.set_channel_types(mapping)
# plot events
mne.viz.plot_events(events_train, event_id=event_id,
sfreq=raw_train.info['sfreq'])
# keep the color-code for further plotting
stage_colors = plt.rcParams['axes.prop_cycle'].by_key()['color']
plt.show()
tmax = 30. - 1. / raw_train.info['sfreq'] # tmax in included
epochs_train = mne.Epochs(raw=raw_train, events=events_train,
event_id=event_id, tmin=0., tmax=tmax, baseline=None)
print(epochs_train)
raw_test = mne.io.read_raw_edf(bob_files[0], stim_channel='Event marker',
infer_types=True)
annot_test = mne.read_annotations(bob_files[1])
annot_test.crop(annot_test[1]['onset'] - 30 * 60,
annot_test[-2]['onset'] + 30 * 60)
raw_test.set_annotations(annot_test, emit_warning=False)
events_test, _ = mne.events_from_annotations(
raw_test, event_id=annotation_desc_2_event_id, chunk_duration=30.)
epochs_test = mne.Epochs(raw=raw_test, events=events_test)
tmin=0., tmax=tmax, baseline=None)
print(epochs_test)
# visualize Alice vs. Bob PSD by sleep stage.
fig, (ax1, ax2) = plt.subplots(ncols=2)
# iterate over the subjects
stages = sorted(event_id.keys())
60
for ax, title, epochs in zip([ax1, ax2],
['Alice', 'Bob'],
[epochs_train, epochs_test]):
for stage, color in zip(stages, stage_colors):
spectrum = epochs[stage].compute_psd(fmin=0.1, fmax=20.)
spectrum.plot(ci=None, color=color, axes=ax,
show=False, average=True, spatial_colors=False)
ax.set(title=title, xlabel='Frequency (Hz)')
ax1.set(ylabel='µV²/Hz (dB)')
ax2.legend(ax2.lines[2::3], stages)
plt.show()
# specific frequency bands
FREQ_BANDS = {"delta": [0.5, 4.5],
"theta": [4.5, 8.5],
"alpha": [8.5, 11.5],
"sigma": [11.5, 15.5],
"beta": [15.5, 30]}
spectrum = epochs.compute_psd(picks='eeg', fmin=0.5, fmax=30.)
psds, freqs = spectrum.get_data(return_freqs=True)
# Normalize the PSDs
psds /= np.sum(psds, axis=-1, keepdims=True)
X = []
for fmin, fmax in FREQ_BANDS.values():
psds_band = psds[:, :, (freqs >= fmin) & (freqs < fmax)].mean(axis=-1)
X.append(psds_band.reshape(len(psds), -1))
return np.concatenate(X, axis=1)
61
pipe = make_pipeline(FunctionTransformer(eeg_power_band, validate=False),
RandomForestClassifier(n_estimators=100, random_state=42))
# Train
y_train = epochs_train.events[:, 2]
pipe.fit(epochs_train, y_train)
# Test
y_pred = pipe.predict(epochs_test)
# Assess the results
y_test = epochs_test.events[:, 2]
acc = accuracy_score(y_test, y_pred)
print("Accuracy score: {}".format(acc))
print(confusion_matrix(y_test, y_pred))
print(classification_report(y_test, y_pred, target_names=event_id.keys()))
def predict1():
import tensorflow as tf
import numpy as np
from tkinter import messagebox
model = tf.keras.models.load_model('Model/cnn.hdf5')
data = np.array([-9,-65,-98,-102,-78,-48,-16,0,-21,-59,-90,-103,-84,-43,-
9,3,21,-27,-96,-103,-75,-29,14,55,78,73,28,-13,-43,-68,-78,-75,-55,-41])
pred = model.predict(data, verbose=0, batch_size=200)
ind = np.argmax(pred)
print(ind)
out = ""
med =''
if ind == 0:
out='Normal'
62
elif ind == 1:
out = 'Stage1'
med ="Benzodiazepines are rapid eye movement (REM) sleep–suppressant,"
elif ind == 2:
out = 'Stage2'
med = "Benzodiazepines are rapid eye movement (REM) sleep–suppressant ,"
elif ind == 3:
out = 'Stage3'
med = "Benzodiazepines are rapid eye movement (REM) sleep–suppressant,"
elif ind == 4:
out = 'Stage4'
med = "Benzodiazepines are rapid eye movement (REM) sleep–suppressant,"
print(out)
messagebox.showinfo("Prediction", "Prediction Result:"+ out)
messagebox.showinfo("Remedy", med)
def Adminlog():
global login_screen
login_screen = Toplevel(main_screen)
login_screen.title("Predict")
login_screen.geometry("600x280")
login_screen.title("Login Form")
global username_verify
global password_verify
username_verify = StringVar()
password_verify = StringVar()
global username_login_entry
63
global password_login_entry
label_0 = Label(login_screen, text="Predict form", width=20, font=("bold",20))
label_0.place(x=90, y=53)
label_1 = Label(login_screen, text="Enter Value", width=20, font=("bold", 10))
label_1.place(x=80, y=130)
username_login_entry = Entry(login_screen, textvariable=username_verify)
username_login_entry.place(x=240, y=130)
bluebutton = Button(login_screen, text="Predict", fg="blue", font=('helvetica')
bluebutton.place(x=220, y=210)
def main_account_screen():
global main_screen
main_screen = Tk()
width = 600
height = 600
screen_width = main_screen.winfo_screenwidth()
screen_height = main_screen.winfo_screenheight()
x = (screen_width / 2) - (width / 2)
y = (screen_height / 2) - (height / 2)
main_screen.geometry("%dx%d+%d+%d" % (width, height, x, y))
main_screen.resizable(0, 0)
# main_screen.geometry("300x250")
main_screen.title("Sleep Abnormal Prediction")
Label(text="Sleep Abnormal Prediction", bg="Blue", width="300”,height="5")
Button(text="Upload Dataset", font=(
'Verdana', 15), height="2", width="30", command=upload,
Label(text="").pack()
64
Button(text="Training", font=(
'Verdana', 15), height="2", width="30", command=training,
Label(text="").pack()
Button(text="Predict", font=(
'Verdana', 15), height="2", width="30", command=Adminlog,
Label(text="").pack()
Button(text="EEG Based Evaluation", font=('Verdana', 15), height="2",
width="30",command=eeeg).pack(side=TOP)
Label(text="").pack()
main_screen.mainloop()
main_account_screen()
65
CHAPTER 10
9.1 CONCLUSION
In conclusion, using a CSV file for sleep stage classification in EEG datasets
can provide valuable information about an individual's sleep patterns. By loading
the EEG data and CSV file into memory and pre-processing the data to extract
relevant features, a labelled dataset of epochs can be created that can be used to
train and evaluate machine learning algorithms. A CNN is a common machine
learning algorithm used for EEG classification, which can learn the relationship
between the EEG features and the sleep stages. The performance of the CNN can
be evaluated using metrics such as accuracy, precision, recall, and F1 score. The
trained CNN can then be used to predict the sleep stage in new EEG datasets by
dividing the data into epochs and classifying each epoch based on its EEG features.
Overall, CSV file classification for EEG datasets provides a powerful tool for sleep
researchers and clinicians to analyze large amounts of sleep data quickly and
accurately. It can help to identify sleep disorders, monitor treatment progress, and
provide insights into the mechanisms of sleep.
While sleeping stage classification using a CSV file and EEG datasets has
shown promising results, there is still room for future work to improve the accuracy
and efficiency of the classification. One area for future work is to explore more
advanced machine learning techniques beyond CNNs. For example, recurrent
neural networks (RNNs) could be used to incorporate temporal information in the
classification process, as sleep stages are known to have temporal dependencies.
66
CHAPTER 11
REFERENCES
67
frequency fluctuation-based machine learning analysis." BMC Psychiatry 23.1
(2023): 1-13.
[11] Rim, Beanbonyka, et al. "Deep learning in physiological signal data: A
survey." Sensors 20.4 (2020): 969.
[12] Mostafa, Sheikh Shanawaz, et al. "A systematic review of detecting sleep
apnea using deep learning." Sensors 19.22 (2019): 4934.
[13] Yildirim, Ozal, Ulas Baran Baloglu, and U. Rajendra Acharya. "A deep
learning model for automated sleep stages classification using PSG
signals." International journal of environmental research and public health 16.4
(2019): 599.
[14] Craik, Alexander, Yongtian He, and Jose L. Contreras-Vidal. "Deep learning
for electroencephalogram (EEG) classification tasks: a review." Journal of neural
engineering 16.3 (2019): 031001.
[15] Hong, Shenda, et al. "Opportunities and challenges of deep learning methods
for electrocardiogram data: A systematic review." Computers in Biology and
Medicine 122 (2020): 103801.
[16] Lashgari, Elnaz, Dehua Liang, and Uri Maoz. "Data augmentation for deep-
learning-based electroencephalography." Journal of Neuroscience Methods 346
(2020): 108885.
[17] Zhang, Xiang, et al. "A survey on deep learning-based non-invasive brain
signals: recent advances and new frontiers." Journal of neural engineering 18.3
(2021): 031002.
[18] Zhu, Tianqi, Wei Luo, and Feng Yu. "Convolution-and attention-based neural
network for automated sleep stage classification." International Journal of
Environmental Research and Public Health 17.11 (2020): 4152.
[19] Shoeibi, Afshin, et al. "Epileptic seizures detection using deep learning
techniques: a review." International Journal of Environmental Research and Public
Health 18.11 (2021): 5780.
[20] Mekruksavanich, Sakorn, and Anuchit Jitpattanakul. "Biometric user
identification based on human activity recognition using wearable sensors: An
experiment using deep learning models" Electronics 10.3 (2021): 308.
68
[21] Zhang, Linda, et al. "Automated sleep stage scoring of the Sleep Heart Health
Study using deep neural networks." Sleep 42.11 (2019): zsz159.
[22] Hosseini, Mohammad-Parsa, Amin Hosseini, and Kiarash Ahi. "A review on
machine learning for EEG signal processing in bioengineering." IEEE reviews in
biomedical engineering 14 (2020): 204-218.
[23] Singh, Himali, Rajesh Kumar Tripathy, and Ram Bilas Pachori. "Detection of
sleep apnea from heart beat interval and ECG derived respiration signals using
sliding mode singular spectrum analysis." Digital Signal Processing 104 (2020):
102796.
[24] Kulkarni, Prathamesh M., et al. "A deep learning approach for real-time
detection of sleep spindles." Journal of neural engineering 16.3 (2019): 036004.
[25] Fukazawa, Yusuke, et al. "Smartphone-based mental state estimation: A
survey from a machine learning perspective." Journal of Information Processing 28
(2020): 16-30.
[26] da Silveira, T.L.T.; Kozakevicius, A.J.; Rodrigues, C.R. Single-channel EEG
sleep stage classification based on a streamlined set of statistical features in wavelet
domain. Med. Biol. Eng. Comput. 2017.
[27] Memar, P.; Faradji, F. A Novel Multi-Class EEG-Based Sleep Stage
Classification System. IEEE Trans. Neural Syst. Rehabil. Eng. 2018.
[28] Yulita, I.N.; Fanany, M.I.; Arymurthy, A.M. Fast convolutional method for
automatic sleep stage classification. Healthc. Inform. Res. 2018
[29] Talo, M.; Baloglu, U.B.; Yıldırım, Ö.; Acharya, U.R. Application of deep
transfer learning for automated brain abnormality classification using MR images.
Cogn. Syst. Res. 2019, 54, 176–188.
[30] Faust, O.; Hagiwara, Y.; Hong, T.J.; Lih, S.; Acharya, R. Deep learning for
healthcare applications based on physiological signals: A review. Comput.
Methods Programs Biomed. 2018.
69
International Journal of Scientific Research in Engineering and Management (IJSREM)
Volume: 07 Issue: 03 | March - 2023 Impact Factor: 7.185 ISSN: 2582-3930
70
International Journal of Scientific Research in Engineering and Management (IJSREM)
Volume: 07 Issue: 03 | March - 2023 Impact Factor: 7.185 ISSN: 2582-3930
71
International Journal of Scientific Research in Engineering and Management (IJSREM)
Volume: 07 Issue: 03 | March - 2023 Impact Factor: 7.185 ISSN: 2582-3930
labelled with sleep stage annotations, and further framework to perform a time aware evaluation of
investigated the identification performance based INSOMNIA on a recently published, revised
on different sleep stages. Our experiments version of CICIDS2017 and demonstrate that
demonstrated that our 1D-CNN leveraging the 3 modern intrusion detection systems must address
sub datasets composed of REM, LSS and SWS concept drift in order to be effective. We envision
epochs, respectively, achieved higher average that future work may build on INSOMNIA in order
accuracy in comparison with baseline methods to design robust intrusion detection models that can
under both intra-patient and inter-patient be sustained over time.
paradigms. The experimental results also To evaluate INSOMNIA, we extend
indicated that amongst all the sleep stages, 1D- TESSERACT—a framework originally proposed
CNN leveraging REM and SWS epochs exhibited for performing sound time-aware evaluations of
the best insomnia identification performance in ML-based malware detectors—to the network
intra-patient paradigm, whereas no statistically intrusion domain and show that accounting for drift
significant difference was found in inter-patient is vital for effective detection. Sharma, Manish,
paradigm. And conducted experiments under et.al,[5] have used a small number of subjects to
intra-patient and inter-patient paradigms, develop the model. This 321 is one of the limitations
respectively. Our experiments demonstrated that of this work. We intend to use more data with a
our 1D-CNN leveraging 3 sub datasets composed greater number of subjects to validate our developed
of REM, LSS and SWS epochs, respectively, system in the future. We are also planning to explore
achieved higher average accuracies in the possibility of developing a deep learning model
comparison with baseline methods under both using huge database. Further, we also plan to extend
intra-patient and inter-patient paradigms. this work using CAP database with other
physiological signals such as multi-modal EEG and
Kuo, Chih-En, et.al,…[3] implemented a EOG. Some other disorders such as bruxism and
short-time insomnia detection system based on a narcolepsy, nocturnal frontal lobe epilepsy (NFLE),
single-channel sleep EOG with RCMSE analysis periodic leg movement (PLM), rapid-eye movement
was proposed. First, a single-channel sleep EOG (REM) behavioural disorder and sleep disordered
was filtered with a band pass filter to remove breathing can also be detected using such automated
artifacts. Second, the RCMSE values with a scale models. Sleep disorders such as sleep movement
factor of 1 to 8 were extracted from the all-night disorders, nocturnal front lobe epilepsy, insomnia,
sleep EOG in 30-s epochs to compare the and narcolepsy are caused due to low sleep quality.
differences between the healthy and insomnia Insomnia is one such sleep disorder where a person
groups. Third, the RCMSE values from the first has difficulty in getting quality sleep. There is no
27.5 min, with scale factor of 1 to 9 were used to definitive test to identify insomnia; hence it is
compute its mean values as the input of classifier. essential to develop an automated system to identify
Finally, the support vector machine (SVM) was it accurately. A few automated methods have been
used to detect insomnia. In addition, MSE and proposed toidentifyinsomnia using either
RCMSE were applied to analyse the sleep EOG polysomnogram (PSG) or electroencephalogram
signals from subjects belonged the different (EEG) signals. To the best of our knowledge, we are
groups, and the MSE and RCMSE values with the first to automatically detect insomnia using only
different sleep stages were also compared electrocardiogram (ECG) signals without
between the healthy and insomnia groups combining them with any other physiological
signals.
Andresini, Giuseppina, et.al,…[4] outlined
a set of open challenges facing modern ML-based
intrusion detectors relating to a lack of uniformity in
the distribution of traffic data over time. To tackle Lee, Mi Hyun, et.al,…[6] investigated the
them, we propose INSOMNIA, a semi-supervised differential spatial covariance pattern of blood
approach that uses active learning to reduce latency oxygen level-dependent (BOLD) responses to
in the model updates, label estimation to reduce single-task and multitask functional magnetic
labelling overhead, and applies explainable AI to resonance imaging (fMRI) between patients with
describe how the model evolves to fit the shifting psychophysiological insomnia (PI) and healthy
distribution. We extend the TESSERACT controls (HCs), and evaluated features generated by
72
International Journal of Scientific Research in Engineering and Management (IJSREM)
Volume: 07 Issue: 03 | March - 2023 Impact Factor: 7.185 ISSN: 2582-3930
73
International Journal of Scientific Research in Engineering and Management (IJSREM)
Volume: 07 Issue: 03 | March - 2023 Impact Factor: 7.185 ISSN: 2582-3930
activities in the right MOG and right cerebellum, problems. It is proven that shallow learning
which might be potential neural markers for techniques are not adequate tools to discriminate
distinguishing HDWI patients from non- among stages (e.g. still there is accuracy
insomniacs, providing further support for the reduction in detecting S1).
pathological mechanism of HDWI. Insomnia is
one of the common problems encountered in the 4. PREPROCESSING
haemodialysis (HD) population, but the The presence of artefacts might lead to the
mechanisms remain unclear. we aimed to (1) misapprehension, low accuracy and distorted
detect the spontaneous brain activity pattern in quantitative results. Therefore, a pre-processing step
HD patients with insomnia (HDWI) by using is necessary to cancel artefacts and remove cropped
fractional amplitude of low frequency fluctuation epochs to magnify informative components of raw
(fALFF) method and (2) further identify brain EEG, EOG and EMG signals prior to any further
regions showing altered fALFF as neural markers analysis. Considering the fact that nowadays
to discriminate HDWI patients from those on portable devices for patient monitoring and
haemodialysis but without insomnia (Hoài) and automatic sleep stage classification could be a
healthy controls (HCs). Resting-state functional helpful assistance for experts on the analysis of sleep
magnetic resonance imaging (rs-fMRI) is a non- signals, the main motivation for the current work is
invasive technique, which could detect the the lack of a systematic method for automatic
ongoing neuronal process at the “resting state” artefact detection and cancellation which leads to an
through measuring the spontaneous brain activity improvement in the automatic stage classification
by low-frequency fluctuations in blood oxygen accuracy compared to the original acquired data
level-dependent (BOLD) signals, and
consequently provide a new opportunity to 5. MULTIPLE CLASSIFIERS FOR
investigate the functional abnormalities on SLEEPING STAGE CLASSIFICATION
several neurological disorders Classification is the process of categorizing
3. MOTIVATION data into relevant groups. The first step in the
classification process is the identification of features
The function of human body is frequently or characteristics that will enable the discrimination
associated with signals of electrical, chemical, or between the different groups of data. A classification
acoustic origin. Such signals convey information model should be developed in a way that provides a
that may not be immediately perceived because it structure for how the classification processes’
is hidden in the signal's structure. However, actions will be realized. Ideally, this model should
signals’ complexity is often considerable and be chosen to optimize the system performance,
therefore, the biomedical signal processing has although it may need to be revised as the classifier
become a vital tool for extracting clinically design progresses. A classifier is then implemented
significant information hidden in signals. The and “trained” to recognize the chosen features in the
artefacts such as body movements, sweating and data, or to determine the best input-to-output
sensor fault can reduce the accuracy in signal mapping. Generally, there are two ways to train a
processing especially in sleep signal analysis. The classifier: supervised learning and unsupervised
conventional solution is to detect the artefacts and learning. A system is called supervised learning if it
denoise the signal by removing corresponding uses data labelled by the expert to create an optimal
epochs from the sleep signal. However, this way, response for the system, which is used as feedback
the EEG signal will be manipulated and may lose to the learning system to increase accuracy. In
important information. One of the motivations of contrast, unsupervised learning occurs when the
this thesis is to develop and improve noise system does not use any labelled data to modify its
cancelation method that does not manipulate the output. Once the system has trained and learned, it
signal and protect its originality. Deep learning is is ready to recognize and classify specific inputs. It
an emerging technique that can be applied to a can be tested and evaluated with such metrics as
broad field of science in order to improve learning speed of computation and accuracy of classification.
and classification algorithms. Deep learning is
rarely used to classify bio signals and still there is
a lack of applying this technique to sleep staging
74
International Journal of Scientific Research in Engineering and Management (IJSREM)
Volume: 07 Issue: 03 | March - 2023 Impact Factor: 7.185 ISSN: 2582-3930
75
International Journal of Scientific Research in Engineering and Management (IJSREM)
Volume: 07 Issue: 03 | March - 2023 Impact Factor: 7.185 ISSN: 2582-3930
70
68
66
64
62
60
58
56
54
Fig 3: Accuracy
6.EXPERIMENTAL RESULTS
From the diagram, convolutional neural network
In this study we can input the EEG provides the improved accuracy than the existing
datasets related to sleeping stages and developed frameworks
in Python framework. Accuracy as main criterion
is considered for evaluating and comparing the 7. CONCLUSION
different classification methods. The performance In this work, we presented an automatic
of the sleep stage classification is evaluated using sleep stage classification model that could achieve
repeated random sub-sampling validation. To good performance on the public dataset and
measure the classification accuracy, the overall accurately predict the sleep stage on our own
accuracy value is calculated as follows laboratory dataset. There are many solutions for
Number of true detections classification of sleep signals. In this paper, we
proposed two methods and explored their utility and
ACCURACY =
benefits in the study of sleep. Convolutional neural
Total number of epochs
network provides improved performance than the
existing machine learning and deep learning.
ALGORITHMS ACCURACY
(%)
SUPPORT VECTOR MACHINE 60
DEEP NEURAL NETWORK 65
76
International Journal of Scientific Research in Engineering and Management (IJSREM)
Volume: 07 Issue: 03 | March - 2023 Impact Factor: 7.185 ISSN: 2582-3930
77