Epileptic Seizure Detection with AI
Epileptic Seizure Detection with AI
CHAPTER 1
INTRODUCTION
Mission:
Our mission at Ether Infotech is to leverage technology to drive business growth and
transformation, while exceeding customer expectations through innovation, integrity, and
quality service delivery.
Vision:
To be a globally recognized leader in providing comprehensive IT solutions and services,
enabling organizations to thrive in the digital era.
Services:
Software Development: Custom software solutions tailored to your business requirements.
Web Development: Responsive and user-friendly web applications and websites.
Mobile Application Development: Native and cross-platform mobile apps for iOS and
Android.
Digital Marketing:
Strategic digital marketing solutions to enhance brand visibility and reach.
IT Consulting:
Expert guidance and support to optimize IT infrastructure and processes.
Healthcare
Finance
E-commerce
Education
2
1.2 OBJECTIVE
The project is structured around several key objectives aimed at advancing the field
of epileptic seizure detection and prediction using artificial neural networks (ANNs).
Firstly, we will focus on acquiring diverse EEG datasets from individuals with epilepsy,
ensuring inclusivity across demographics and seizure types. These datasets will undergo
meticulous preprocessing to remove noise and artifacts, ensuring the neural network
models receive clean and reliable input data. Subsequently, we will explore and develop
various ANN architectures, including convolutional neural networks (CNNs) and recurrent
neural networks (RNNs), tailored specifically for seizure detection and prediction tasks.
These models will be trained on the preprocessed EEG data, with parameters optimized to
maximize performance. Additionally, we will extract relevant features from the EEG
signals, such as spectral power and wavelet coefficients, to provide informative input to the
neural networks. Through rigorous training, validation, and testing procedures, we aim to
evaluate the efficacy of our models in accurately detecting and predicting seizure events.
Ultimately, our project seeks to integrate these advanced neural network models into
clinical practice, contributing to improved patient care and management of epilepsy by
enabling early intervention and personalized treatment strategies.
3
CHAPTER 2
SYSTEM ANALYSIS
2.1.1. Disadvantage
Accuracy is less
Limited Accessibility
2.2.1. Advantages
The purpose of this chapter is to introduce the reader to feasibility studies, project
appraisal, and investment analysis. Feasibility studies are an example of systems analysis.
A system is a description of the relationships between the inputs of labour, machinery,
materials and management procedures, both within an organisation and between an
organisation and the outside world.
During the planning and execution stages of an audit, it’s important to have a clear
understanding of what the objectives of the audit include. Companies should strive to align
their business objectives with the objectives of the audit. This will ensure that time and
resources spent will help achieve a strong internal control environment and lower the risk
of a qualified opinion.
Once the technical feasibility is established, it is important to consider the monetary factors
also. Since it might happen that developing a particular system may be technically possible
but it may require huge investments and benefits may be less. For evaluating this,
economic feasibility of the proposed system is carried out.
7
Economic feasibility analysis is the most commonly used method for determining
the efficiency of a new project. It is also known as cost analysis. It helps in identifying
profit against investment expected from a project. Cost and time are the most essential
factors involved in this field of study. For any system if the expected benefits equal or
exceed the expected costs, the system can be judged to be economically feasible. In
economic feasibility, cost benefit analysis is done in which expected costs and benefits are
evaluated. Economic analysis is used for evaluating the effectiveness of the proposed
system.
8
CHAPTER 3
SYSTEM SPECIFICATION
CHAPTER 4
SOFTWARE DESCRIPTION
PYTHON
It was first released in 1991 by Guido van Rossum and has since become one of the
most popular programming languages due to its simplicity, readability, and versatility. One
of the key features of Python is its easy-to-learn syntax, which makes it accessible to both
novice and experienced programmers. It has a large standard library that provides a wide
range of modules for tasks such as file I/O, networking, regular expressions, and more.
Python also has a large and active community of developers who contribute to
open-source libraries and packages that extend its capabilities. Python is an interpreted
language, which means that it is executed line-by-line by an interpreter rather than
compiled into machine code like C or C++.
This allows for rapid development and testing, as well as easier debugging and
maintenance of code. Python is used for a variety of applications, including web
development frameworks such as Django and Flask, scientific computing libraries such as
NumPy and Pandas, and machine learning libraries such as TensorFlow and PyTorch. It is
also commonly used for scripting and automation tasks due to its ease of use and
readability. Overall, Python is a powerful and versatile programming language that is
widely used in a variety of domains due to its simplicity, ease of use, and active
community.
10
MYSQL
ACID Compliance: MySQL ensures that database transactions are reliable, even in the
event of power failures or crashes, by following the ACID (Atomicity, Consistency,
Isolation, Durability) properties.
Scalability: MySQL can handle large volumes of data and high traffic loads, making it
suitable for both small-scale and enterprise-level applications.
Security: MySQL provides robust security features, including user authentication, access
control, encryption, and data masking, to protect sensitive information.
Community and Support: MySQL has a large and active community of developers and
Users who contribute to its development, provide support, and share knowledge through
forums, documentation, and tutorials.
4.3 PYCHARM
Features:
Intelligent code completion
Syntax highlighting
Code inspection
Code navigation and search
Debugging
Testing
Version control integration
Web development support
Scientific tools support
Database tools support
Mercurial, and Subversion. The IDE also has features specifically geared towards web
development, such as support for popular web frameworks like Django, Flask, and
Pyramid. It includes tools for debugging, testing, and profiling web applications. PyCharm
also provides scientific tools for data analysis, visualization, and scientific computing, such
as support for NumPy, SciPy, and matplotlib. It also includes tools for working with
databases, such as PostgreSQL, MySQL, and Oracle. Overall, PyCharm is a powerful and
feature-rich IDE that can greatly increase productivity for Python developers.
Customization:
PyCharm allows developers to customize the IDE to their liking. Users can change
the color scheme, fonts, and other settings to make the IDE more comfortable to use.
PyCharm also supports plugins, which allow developers to extend the IDE with additional
features.
Collaboration:
PyCharm makes it easy for developers to collaborate on projects. It supports
integration with popular collaboration tools such as GitHub, Bitbucket, and GitLab. It also
includes features for code reviews, task management, and team communication.
Education:
PyCharm provides a learning environment for Python programming language.
PyCharm Edu is a free, open-source edition of PyCharm that includes interactive courses
and tutorials for learning Python. It provides an easy-to-use interface for beginners and
includes features such as code highlighting, autocompletion, and error highlighting.
Support:
PyCharm has an active community of users who provide support through forums
and social media. JetBrains also provides comprehensive documentation, tutorials, and
training courses for PyCharm. For users who need more personalized support, JetBrains
offers a paid support plan that includes email and phone support.
Pricing:
PyCharm Community Edition is free and open-source. PyCharm Professional
Edition requires a paid license, but offers a 30-day free trial. JetBrains also offers a
subscription-based pricing model that includes access to all JetBrains IDEs and tools.
13
Integrations:
PyCharm integrates with a wide range of tools and technologies commonly used in
Python development. It supports popular Python web frameworks like Flask, Django,
Pyramid, and web2py. It also integrates with tools for scientific computing like NumPy,
SciPy, and pandas. PyCharm also supports popular front-end technologies such as HTML,
CSS, and JavaScript.
Performance:
PyCharm is known for its fast and reliable performance. It uses a combination of
static analysis, incremental compilation, and intelligent caching to provide fast code
completion and navigation. PyCharm also has a memory profiler that helps identify and
optimize memory usage in Python applications.
Ease of Use:
PyCharm provides an intuitive and easy-to-use interface for developers. It has a
well-organized menu structure, clear icons, and easy-to-navigate tabs. PyCharm also
provides a variety of keyboard shortcuts and customizable keymaps that allow users to
work efficiently without constantly switching between the mouse and keyboard.
Community:
PyCharm has a large and active community of developers who contribute to the
development of the IDE. The PyCharm Community Edition is open-source, which means
that anyone can contribute to its development. The PyCharm user community is also active
in providing support, tips, and tutorials through forums, blogs, and social media.
14
CHAPTER 5
PROJECT DESCRIPTION
The problem we aim to address is the need for more accurate and timely detection
and prediction of epileptic seizures. Epilepsy, a neurological disorder characterized by
recurrent seizures, affects millions of individuals worldwide, significantly impacting their
quality of life. Current methods for seizure detection and prediction often lack precision
and may not provide sufficient warning time for timely intervention. This poses challenges
for patients and caregivers in managing the condition effectively and minimizing the
potential risks associated with seizures, such as injury or loss of consciousness. Therefore,
our goal is to develop an advanced solution utilizing artificial neural networks to improve
the accuracy, reliability, and timeliness of epileptic seizure detection and prediction,
ultimately enhancing patient outcomes and quality of [Link] advancements in medical
technology, accurate and timely detection of epileptic seizures remains a significant
challenge. The current methods often rely on manual interpretation of EEG signals by
healthcare professionals, which can be subjective, time-consuming, and prone to errors.
Automated seizure detection systems have been developed, but they may suffer from high
false alarm rates or limited sensitivity, leading to missed or misclassified seizure events.
Additionally, predicting seizures before they occur is a complex task, as seizure onset can
vary widely among individuals and may not always follow predictable patterns. This lack
of reliable seizure prediction hinders the implementation of preventive measures or timely
administration of medication to mitigate seizure severity.
15
Datasets Acquisition
Preprocessing
Features Extraction
Classification
5.3.1 DATASETS ACQUISITION
5.3.2 PREPROCESSING
Data preprocessing can refer to manipulation or dropping of data before it is used in
order to ensure or enhance performance, and is an important step in the data mining
process. The phrase "garbage in, garbage out" is particularly applicable to data mining and
machine learning projects. Data-gathering methods are often loosely controlled, resulting
in out-of-range values, impossible data combinations and missing values, etcOften, data
preprocessing is the most important phase of a machine learning project, especially in
computational biology. In the pre-processing stage, continuous EEG recordings are firstly
segmented without overlapping by a sliding time window. Then wavelet transform is
performed on the EEG data to provide the signals form of dataset.
17
In this module, we can extract the time and frequency domain features from
preprocessed data. It includes “mean”, variance", "kurtosis", "skewness” and other features
for future classification. Mean: It is the average of an N sample EEG signal; it can be
defined
𝑁
1
𝜇 = ∑ 𝑌𝑖
𝑁
𝑖=1
Standard deviation: The dispersion of data from it’s a mean value of a signal is a standard
deviation.
𝑁
1
𝜎=√ ∑(𝑌𝑖 − 𝜇)2
𝑁−1
𝑖=1
Kurtosis: It is a one of the statistical moment; it gives the time series data peaked nature.
Kurtosis can be derived as
𝑁
1 𝑦𝑖−𝜇 4
𝑘 = ∑( )
𝑁 𝜎
𝑖=1
Skewness: It measures the symmetry shape of the distribution of a signal, It can be derived
as
𝑁
1 𝑦𝑖−𝜇 3
𝑠𝑘𝑒𝑤𝑛𝑒𝑠𝑠 = ∑( )
𝑁 𝜎
𝑖=1
5.3.4 CLASSIFICATION
every neuron in another layer. The CNN is in principle the same as the traditional multi-
layer perceptron neural network. Compared with traditional classifiers, CNNs have
obvious advantages for analyzing high-dimensional data. CNNs employ a parameter
sharing scheme, which is used in convolutional layers to control and reduce the number of
parameters..
So our proposed work overcomes outlier’s separation in EEG data classification with
features extraction. Based on classification we can predict the seizure and non-seizure data
and predict the Epilepsy with SMS alert
Asourceofsysteminputsor sink
Externalentity
of system outputs
Database Arepositoryofdata;the
arrowheadsindicatenet
inputsandnetoutputsto
store
21
LEVEL 0
LEVEL 1
LEVEL 2
LEVEL3
System
Datasetsupload
Preprocessing
User
Featuresextraction
Classification
Seizuredetection
Dataset upload
Preprocessing
Features extraction
Classification
Seizure detection
The input design is the link between the information system and the user. It
comprises the developing specification and procedures for data preparation and those steps
are necessary to put transaction data in to a usable form for processing can be achieved by
inspecting the computer to read data from a written or printed document or it can occur by
having people keying the data directly into the system. The design of input focuses on
controlling the amount of input required, controlling the errors, avoiding delay, avoiding
extra steps and keeping the process simple. The input is designed in such a way so that it
provides security and ease of use with retaining the privacy. Input Design considered the
following things:
OBJECTIVES
Input Design is the process of converting a user-oriented description of the input
into a computer-based system. This design is important to avoid errors in the data
input process and show the correct direction to the management for getting correct
information from the computerized system.
It is achieved by creating user-friendly screens for the data entry to handle large
volume of data. The goal of designing input is to make data entry easier and to be
free from errors. The data entry screen is designed in such a way that all the data
manipulates can be performed. It also provides record viewing facilities.
When the data is entered it will check for its validity. Data can be entered with the
help of screens. Appropriate messages are provided as when needed so that the user
will not be in maize of instant. Thus the objective of input design is to create an
input layout that is easy to follow.
The NetBeans 7.4 and later uses the new Nashorn JavaScript engine developed by
Oracle. Users can choose to download NetBeans IDE bundles tailored to specific
26
development needs. Users can also download and install all other features at a later
date directly through theNetBeans IDE.
The output form of an information system should accomplish one or more of the following
objectives.
Convey information about past activities, current status or projections of the
Future.
Signal important events, opportunities, problems, or warnings.
Trigger an action.
Confirm an action.
Implementation is the stage of the project when the theoretical design is turned out into
a working system. Thus it can be considered to be the most critical stage in achieving a
successful new system and in giving the user, confidence that the new system will work
and be effective.
27
CHAPTER 6
SYSTEM TESTING
The purpose of testing is to discover errors. Testing is the process of trying to discover
every conceivable fault or weakness in a work product. It provides a way to check the
functionality of components, sub assemblies, assemblies and/or a finished product It is the
process of exercising software with the intent of ensuring that the Software system meets
its requirements and user expectations and does not fail in an unacceptable manner. There
are various types of test. Each test type addresses a specific testing requirement.
TYPES OF TESTING
SYSTEM TESTING
System testing ensures that the entire integrated software system meets
requirements. It tests a configuration to ensure known and predictable results. An example
of system testing is the configuration oriented system integration test. System testing is
based on process descriptions and flows, emphasizing pre-driven process links and
integration points.
White Box Testing is a testing in which in which the software tester has
knowledge of the inner workings, structure and language of the software, or at least its
purpose. It is purpose. It is used to test areas that cannot be reached from a black box level.
29
Features to be tested
Verify that the entries are of the correct format
No duplicate entries should be allowed
All links should take the user to the correct page.
INTEGRATION TESTING
Software integration testing is the incremental integration testing of two or
more integrated software components on a single platform to produce failures caused by
interface defects.
The task of the integration test is to check that components or software
applications, e.g. components in a software system or level interact without error. one step
up software applications at the company
TEST RESULTS: All the test cases mentioned above passed successfully. No defects
encountered.
30
CHAPTER 7
SYSTEM IMPLEMENTATION
Data Acquisition: The system typically begins with the acquisition of physiological data,
such as EEG signals, which are essential for epilepsy detection and monitoring. This may
involve using specialized EEG devices or wearable sensors capable of capturing brain
activity.
Signal Processing: Once the data is acquired, signal processing techniques are applied to
preprocess and extract relevant information from the EEG signals. This may include
filtering out noise, artifact removal, and feature extraction to identify patterns associated
with epileptic seizures.
Feature Extraction: Features such as spectral power, frequency bands, time-domain
characteristics, and statistical measures are extracted from the preprocessed EEG signals.
These features serve as input to machine learning or statistical algorithms for seizure
detection and classification.
Detection Algorithms: Various algorithms, including machine learning models (e.g.,
SVM, CNN) and signal processing techniques, are employed for seizure detection. These
algorithms analyze the extracted features to distinguish between normal brain activity and
epileptic seizures.
Classification and Decision Making: Seizure detection algorithms classify EEG segments
into seizure or non-seizure categories based on predefined criteria. They may also provide
additional information such as seizure onset time, duration, and severity to aid in clinical
decision-making.
Real-time Monitoring: For continuous monitoring of epilepsy patients, the system should
be capable of real-time processing and analysis of EEG data. This enables timely detection
and notification of seizure events, allowing for prompt intervention and treatment.
User Interface: A user-friendly interface is essential for interacting with the system,
displaying EEG data, visualization of detected seizures, and providing alerts or
notifications to caregivers or healthcare professionals. The interface should be intuitive,
accessible, and customizable to meet the needs of different users.
31
CHAPTER 8
8.1 CONCLUSION
CHAPTER 9
APPENDICES
[Link](131)
[[Link]([Link][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())
[Link]()
data = [Link]('Unnamed', axis = 1)
data = shuffle(data)
[Link]()
[Link]()
print('Number of records of Non Epileptic {0} VS Epilepttic {1}'.format(len(data[data['y']
== 0]), len(data[data['y'] == 1])))
data[data['y'] == 0].describe().T
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 Epiletic: {}'.format((data[data['y'] ==
1].describe().mean()).mean()))
print('Totall Std VALUE for Epiletic: {}'.format((data[data['y'] ==
1].describe().std()).std()))
print('Totall Mean VALUE for NON Epiletic: {}'.format((data[data['y'] ==
0].describe().mean()).mean()))
print('Totall Std VALUE for NON Epiletic: {}'.format((data[data['y'] ==
0].describe().std()).std()))
[([Link](figsize=(8,4)), [Link]('Not Epileptic'), [Link](data[data['y'] == 0].iloc[i][0:-
1])) for i in range(5)];
[([Link](figsize=(8,4)), [Link]('Epileptic'), [Link](data[data['y'] == 1].iloc[i][0:-1])) for
i in range(5)];
#lists of arrays containing all data without y column
not_epileptic = [data[data['y']==0].iloc[:, range(0, len([Link])-1)].values]
epileptic = [data[data['y']==1].iloc[:, range(0, len([Link])-1)].values]
#We will create and calculate 2d indicators in order plot data in 2 dimensions;
34
def indic(data):
"""Indicators can be different. In our case we use just min and max values
Additionally, it can be mean and std or another combination of indicators"""
max = [Link](data, axis=1)
min = [Link](data, axis=1)
return max, min
x1,y1 = indic(not_epileptic)
x2,y2 = indic(epileptic)
fig = [Link](figsize=(14,6))
ax1 = fig.add_subplot(111)
[Link](x1, y1, s=10, c='b', label='Not Epiliptic')
[Link](x2, y2, s=10, c='r', label='Epileptic')
[Link](loc='lower left');
[Link]()
#Just Epileptic
x,y = indic(data[data['y']==1].iloc[:, range(0, len([Link])-1)].values)
[Link](figsize=(14,4))
[Link]('Epileptic')
[Link](x, y, c='r');
[Link]()
x,y = indic(data[data['y']==0].iloc[:, range(0, len([Link])-1)].values)
[Link](figsize=(14,4))
[Link]('NOT Epileptic')
[Link](x, y);
[Link]()
# define oversampling strategy
oversample =
imblearn.over_sampling.RandomOverSampler(sampling_strategy='minority')
# fit and apply the transform
X, y = oversample.fit_resample([Link]('y', axis=1), data['y'])
[Link], [Link]
print('Number of records of Non Epileptic {0} VS Epilepttic {1}'.format(len(y == True),
len(y == False)))
35
normalized_df = [Link](normalize(X))
normalized_df
#Concat back in order to check description:
normalized_df['y'] = y
print('Normalized Totall Mean VALUE for Epiletic:
{}'.format((normalized_df[normalized_df['y'] == 1].describe().mean()).mean()))
print('Normalized Totall Std VALUE for Epiletic:
{}'.format((normalized_df[normalized_df['y'] == 1].describe().std()).std()))
print('Normalized Totall Mean VALUE for NOT Epiletic:
{}'.format((normalized_df[normalized_df['y'] == 0].describe().mean()).mean()))
print('Normalized Totall Std VALUE for NOT Epiletic:
{}'.format((normalized_df[normalized_df['y'] == 0].describe().std()).std()))
'''#Let us split our dataset on train and test and than invoke validation approach
X = normalized_df.drop('y', axis=1)
Y = normalized_df['y']
#X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.3, random_state=42)
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.20, random_state=1)
#Check the shapes after splitting
#he = X_train, X_test, y_train, y_test
#[[Link] for arr in he]
model = Sequential()
[Link](Conv1D(filters=2048, kernel_size=3, activation='relu', input_shape=(178,1)))
[Link](Dropout(0.5))
# [Link](MaxPooling1D(pool_size=3))
[Link](Conv1D(filters=1024, kernel_size=3, activation='relu'))
[Link](Dropout(0.5))
[Link](Conv1D(filters=512, kernel_size=3, activation='relu'))
[Link](Dropout(0.5))
[Link](Conv1D(filters=256, kernel_size=3, activation='relu'))
[Link](Dropout(0.3))
[Link](Conv1D(filters=128, kernel_size=3, activation='relu'))
[Link](Dropout(0.3))
36
[Link]()
def upload():
import Main as mm
#del [Link]["Main"]
def training():
import Train astt
# del [Link]["Train"]
def testing():
import Test aste
#del [Link]["Test"]
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("FEpileptic Seizure Recognition")
Label(text="Epileptic Seizure Recognition", bg="Blue", width="300", height="5",
font=("Calibri", 16)).pack()
Button(text="Upload Dataset", font=(
'Verdana', 15), height="2", width="30", command=upload,
highlightcolor="black").pack(side=TOP)
Label(text="").pack()
Button(text="Training", font=(
'Verdana', 15), height="2", width="30", command=training,
highlightcolor="black").pack(side=TOP)
38
Label(text="").pack()
Button(text="Testing", font=('Verdana', 15), height="2",
width="30",command=testing).pack(side=TOP)
Label(text="").pack()
main_screen.mainloop()
main_account_screen()
#from [Link] import classification_report
#from [Link] import precision_recall_fscore_support
import tensorflow as tf
import numpy as np
from tkinter import messagebox
model = [Link].load_model('cnn_epil.hdf5')
data = [Link]([[593,328,88,-106,-456,-732,-921,-782,-522,-248,-
68,89,221,342,336,219,82,-32,-83,-114,-134,-134,-113,-101,-109,-112,-117,-103,-83,-
20,220,564,957,1162,1125,975,807,715,677,425,40,-553,-950,-993,-
554,49,574,816,732,495,61,-312,-497,-463,-258,-73,35,73,66,24,-19,-44,-48,-52,-48,-
19,33,94,148,184,206,215,233,228,231,233,226,239,242,265,263,203,66,-108,-272,-373,-
422,-406,-363,-309,-257,-207,-178,-151,-134,-69,208,593,918,867,602,220,-163,-553,-
888,-1015,-880,-568,-216,76,288,360,284,116,-93,-253,-314,-308,-272,-247,-251,-249,-
239,-225,-222,-237,-269,-287,-259,-202,-
51,258,610,993,1096,1016,856,721,695,678,477,103,-471,-831,-889,-541,-
94,284,436,321,128,-131,-332,-358,-320,-203,-
80,23,103,151,169,173,176,173,172,191,217,248,271,312,360,421,445,413,310,177,41,-
71]])
pred=[Link](data, verbose=0, batch_size=200)
pred=[Link](pred)
i = 0;
for elem in pred[0]:
i += 1
if(elem == 1 ):
print(i)
if(i==1):
#sendmsg("","Epilepttic")
39
print('Yes')
[Link]("Result", "Epilepttic")
else:
#sendmsg("", "Non-Epilepttic")
[Link]("Result", "Non-Epilepttic")
#print('No')
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
data=pd.read_csv('Data/Train/Epileptic Seizure [Link]')
import tensorflow as tf
import numpy as np
from [Link] import Sequential
from [Link] import np_utils
#from [Link] import to_categorical
from [Link] import Dense, Activation,Conv1D,MaxPooling1D, Dropout, Flatten
import pandas as pd
import [Link] as plt
[Link]()
from [Link] import LabelBinarizer
X=[Link]([Link])
X=[Link](X[:,1:-1])
X=[Link](float)
minm=[Link]()
maxm=[Link]()
X_norm=(X-minm)/(maxm-minm)
print([Link])
from sklearn.model_selection import train_test_split
mlb = LabelBinarizer()
y=[Link](data['y'])
# y=[Link]('float')
# Y=mlb.fit_transform(y)
Y=[Link](float)
#X=[Link](1200,178,1)
40
#print([Link])
Y=Y-1
Y
#from [Link]. import to_categorical
#from [Link].np_utils import to_categorical
from [Link].np_utils import to_categorical
Y = to_categorical(Y)
Y
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.20, random_state=42)
model = Sequential()
[Link](Conv1D(filters=2048, kernel_size=3, activation='relu', input_shape=(178,1)))
[Link](Dropout(0.5))
# [Link](MaxPooling1D(pool_size=3))
[Link](Conv1D(filters=1024, kernel_size=3, activation='relu'))
[Link](Dropout(0.5))
[Link](Conv1D(filters=512, kernel_size=3, activation='relu'))
[Link](Dropout(0.5))
[Link](Conv1D(filters=256, kernel_size=3, activation='relu'))
[Link](Dropout(0.3))
[Link](Conv1D(filters=128, kernel_size=3, activation='relu'))
[Link](Dropout(0.3))
[Link](Conv1D(filters=128, kernel_size=3, activation='relu'))
[Link](Dropout(0.3))
[Link](Conv1D(filters=64, kernel_size=3, activation='relu'))
[Link](Dropout(0.3))
[Link](Conv1D(filters=32, kernel_size=3, activation='relu'))
[Link](Dropout(0.3))
[Link](MaxPooling1D(pool_size=2))
[Link](Flatten())
# [Link](Dense(32, activation='relu'))
[Link](Dense(5, activation='softmax'))
# [Link](loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
[Link]()
41
[Link](optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])
y_ints = [[Link]() for y in Y_train]
from [Link] import class_weight
class_weights = class_weight.compute_class_weight('balanced',
[Link](y_ints),
y_ints)
class_weight_dict = dict(enumerate(class_weights))
#class_weight_dict
from [Link] import EarlyStopping
from [Link] import ModelCheckpoint
# earlyStopping = EarlyStopping(monitor='val_loss', patience=50, verbose=0, mode='min')
mcp_save = ModelCheckpoint('cnn_epil.hdf5', save_best_only=True,verbose=1,
monitor='val_accuracy', mode='max')
[Link](X_train,Y_train,100,70,verbose=1,callbacks=[mcp_save], validation_split=0.2)#,
class_weight=class_weight_dict)
from [Link] import classification_report
from [Link] import precision_recall_fscore_support
scores = [Link](X_test, Y_test, verbose=0, batch_size=200)
pred=[Link](X_test, verbose=0, batch_size=200)
pred=[Link](pred)
print(classification_report(Y_test, pred))
f1=precision_recall_fscore_support(Y_test, pred, average='micro')
print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
42
9.2 SCREENSHOTS
0 9200
1 2300
Name: y, dtype: int64
<class '[Link]'>
Int64Index: 11500 entries, 8039 to 8114
Columns: 179 entries, X1 to y
43
dtypes: int64(179)
memory usage: 15.8 MB
Number of records of Non Epileptic 9200 VS Epilepttic 2300
count mean std min 25% 50% 75% max
X1 9200.0 -8.992609 70.455286 -566.0 -44.0 -7.0 26.0 1726.0
X2 9200.0 -8.877174 70.560110 -609.0 -44.0 -7.0 27.0 1713.0
X3 9200.0 -8.910435 70.372582 -594.0 -45.0 -7.0 28.0 1697.0
X4 9200.0 -8.969783 70.030409 -549.0 -45.0 -8.0 27.0 1612.0
X5 9200.0 -9.085326 69.377958 -603.0 -45.0 -8.0 27.0 1437.0
... ... ... ... ... ... ... ... ...
X175 9200.0 -9.848587 69.550894 -570.0 -45.0 -9.0 27.0 1958.0
X176 9200.0 -9.620435 70.353607 -594.0 -46.0 -8.0 27.0 2047.0
X177 9200.0 -9.395435 70.934300 -563.0 -45.0 -9.0 27.0 2047.0
X178 9200.0 -9.240435 71.185850 -559.0 -45.0 -8.0 27.0 1915.0
y 9200.0 0.000000 0.000000 0.0 0.0 0.0 0.0 0.0
2022-04-09 16:51:37.359511: W
tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic
library 'cudart64_110.dll'; dlerror: cudart64_110.dll not found
2022-04-09 16:51:45.433352: W
tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic
library '[Link]'; dlerror: [Link] not found
To enable them in other operations, rebuild TensorFlow with the appropriate compiler
flags.
Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
================================================================
=
conv1d (Conv1D) (None, 176, 2048) 8192
================================================================
=
Total params: 8,459,013
Trainable params: 8,459,013
Non-trainable params: 0
53
54
CHAPTER 10
REFERENCES
[1] Zhang, Yanli, Rendi Yang, and Weidong Zhou. "Roughness-length-based characteristic
analysis of intracranial eeg and epileptic seizure prediction." International Journal of
Neural Systems 30.12 (2020): 2050072.
[2] Zarei, Asghar, and Babak Mohammadzadeh Asl. "Automatic seizure detection using
orthogonal matching pursuit, discrete wavelet transform, and entropy based features of
EEG signals." Computers in Biology and Medicine 131 (2021): 104250.
[3] Faust, Oliver, et al. "Automatic identification of epileptic and background EEG signals
using frequency domain parameters." International journal of neural systems 20.02 (2010):
159-176.
[4] Riaz, Farhan, et al. "EMD-based temporal and spectral features for the classification of
EEG signals using supervised learning." IEEE Transactions on Neural Systems and
Rehabilitation Engineering 24.1 (2015): 28-35.
[5] Craley, Jeff, et al. "Automated inter-patient seizure detection using multichannel
convolutional and recurrent neural networks." Biomedical Signal Processing and
Control 64 (2021): 102360.
[6] Tanveer, M. Asjid, et al. "Convolutional neural networks ensemble model for neonatal
seizure detection." Journal of Neuroscience Methods 358 (2021): 109197.
10.2WEB REFERENCE
[1] [Link]
[2] [Link]
[3] [Link]