astro21 commited on
Commit
55649e9
·
1 Parent(s): fd6f396

Upload 2 files

Browse files
Files changed (2) hide show
  1. README.md +1 -13
  2. main.py +286 -0
README.md CHANGED
@@ -1,13 +1 @@
1
- ---
2
- title: Eeg Classification Def
3
- emoji: 👁
4
- colorFrom: gray
5
- colorTo: yellow
6
- sdk: streamlit
7
- sdk_version: 1.29.0
8
- app_file: app.py
9
- pinned: false
10
- license: mit
11
- ---
12
-
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
+ # eeg_classification_def
 
 
 
 
 
 
 
 
 
 
 
 
main.py ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import mne
3
+ import os
4
+ import numpy as np
5
+ import pandas as pd
6
+ import joblib
7
+ from scipy import stats
8
+ import sklearn
9
+ from sklearn.preprocessing import StandardScaler
10
+ from xgboost import XGBClassifier
11
+ from sklearn.decomposition import PCA
12
+ from PIL import Image
13
+
14
+ st.set_page_config(layout="wide", page_title="EEG Classification", page_icon=":brain:")
15
+
16
+ # load assets
17
+ sml_poster = Image.open("poster/SML_EEG.png")
18
+ sml_ppt = Image.open("poster/SML_ProjectReview.png")
19
+ dataset_img = Image.open("poster/data.png")
20
+ about_img = Image.open("poster/about.png")
21
+
22
+
23
+ # define a function to read the data from the .set file
24
+ def read_data(file_path):
25
+ data = mne.io.read_raw_eeglab(file_path, preload=True)
26
+ data.apply_function(lambda x: np.convolve(x, np.ones(50) / 50, mode='same'))
27
+ data.set_eeg_reference()
28
+ data.filter(l_freq=1, h_freq=50)
29
+ epochs = mne.make_fixed_length_epochs(data, duration=1, preload=True)
30
+ array = epochs.get_data()
31
+ return array
32
+
33
+
34
+ def pca_to_epochs(file_path, n_components=15, epoch_length=1, sfreq=250):
35
+ # eeg_data is a numpy array of shape (n_channels, n_samples)
36
+ eeg_data = mne.io.read_raw_eeglab(file_path, preload=True)
37
+ eeg_data.apply_function(lambda x: np.convolve(x, np.ones(50) / 50, mode='same'))
38
+ eeg_data.set_eeg_reference()
39
+ eeg_data.filter(None, 50., fir_design='firwin')
40
+ # Apply PCA to the EEG data
41
+ pca = PCA(n_components=n_components)
42
+ pca_data = pca.fit_transform(eeg_data.get_data().T) # Transpose data to shape (n_samples, n_channels) for PCA
43
+
44
+ # Create an MNE RawArray object from the PCA data
45
+ channel_names = ['PC{}'.format(i + 1) for i in range(n_components)]
46
+ info = mne.create_info(channel_names, sfreq, ch_types='eeg')
47
+ raw_pca = mne.io.RawArray(pca_data.T, info)
48
+
49
+ # Convert the RawArray to epochs
50
+ tmax = epoch_length - 1 / sfreq # Adjust tmax to account for last sample in epoch
51
+ events = mne.make_fixed_length_events(raw_pca, duration=epoch_length)
52
+ epochs = mne.Epochs(raw_pca, events=events, tmin=0, tmax=tmax, baseline=None, preload=True)
53
+
54
+ return epochs.get_data()
55
+
56
+
57
+ def ica_to_epochs(file_path, n_components=12, epoch_length=1, sfreq=250):
58
+ # eeg_data is a numpy array of shape (n_channels, n_samples)
59
+ eeg_data = mne.io.read_raw_eeglab(file_path , preload=True)
60
+ eeg_data.apply_function(lambda x: np.convolve(x, np.ones(50)/50, mode='same'))
61
+ eeg_data.set_eeg_reference()
62
+ eeg_data.filter(None, 50., fir_design='firwin')
63
+ # Apply ICA to the EEG data
64
+ ica = mne.preprocessing.ICA(n_components=n_components, random_state=97)
65
+ ica.fit(eeg_data)
66
+ # Apply the ICA to the raw data
67
+ raw_ica = ica.apply(eeg_data.copy(), exclude=ica.exclude)
68
+
69
+ # Convert the RawArray to epochs
70
+ tmax = epoch_length - 1/sfreq # Adjust tmax to account for last sample in epoch
71
+ events = mne.make_fixed_length_events(raw_ica, duration=epoch_length)
72
+ epochs = mne.Epochs(raw_ica, events=events, tmin=0, tmax=tmax, baseline=None, preload=True)
73
+
74
+ return epochs.get_data()
75
+
76
+
77
+ def mean(x):
78
+ return np.mean(x, axis=-1)
79
+
80
+
81
+ def std(x):
82
+ return np.std(x, axis=-1)
83
+
84
+
85
+ def ptp(x):
86
+ return np.ptp(x, axis=-1)
87
+
88
+
89
+ def skew(x):
90
+ return stats.skew(x, axis=-1)
91
+
92
+
93
+ def var(x):
94
+ return np.var(x, axis=-1)
95
+
96
+
97
+ def min(x):
98
+ return np.min(x, axis=-1)
99
+
100
+
101
+ def max(x):
102
+ return np.max(x, axis=-1)
103
+
104
+
105
+ def argmin(x):
106
+ return np.argmin(x, axis=-1)
107
+
108
+
109
+ def argmax(x):
110
+ return np.argmax(x, axis=-1)
111
+
112
+
113
+ def rms(x):
114
+ return np.sqrt(np.mean(x ** 2, axis=-1))
115
+
116
+
117
+ def abs_diff_signal(x):
118
+ return np.sum(np.abs(np.diff(x, axis=-1)), axis=-1)
119
+
120
+
121
+ def kurtosis(x):
122
+ return stats.kurtosis(x, axis=-1)
123
+
124
+
125
+ def concatenate_fucntions(x):
126
+ return np.concatenate((mean(x), std(x), ptp(x), skew(x), var(x), min(x), max(x), rms(x), argmin(x), argmax(x),
127
+ abs_diff_signal(x), kurtosis(x)), axis=-1)
128
+
129
+
130
+ def model():
131
+ uploaded_file = st.file_uploader("Upload a .set file", type=".set")
132
+
133
+ if uploaded_file is not None:
134
+ # save the uploaded file to disk
135
+ file_path = os.path.join("./", uploaded_file.name)
136
+ with open(file_path, "wb") as f:
137
+ f.write(uploaded_file.getbuffer())
138
+
139
+ # read the data from the uploaded file
140
+
141
+ st.header("Customizing the model.")
142
+ model_name_display = ["Logistic Regression", "KNN", "Random Forest", "Decision Tree", "XGBoost"]
143
+ model_ = st.selectbox("Select the model",model_name_display)
144
+ # get model index from model name
145
+ model_index = model_name_display.index(model_)
146
+ # create a radio button to select between ICA, PCA, and None
147
+ model_names = ['logReg.pkl', 'knn.pkl', 'randomForest.pkl', 'decisionTree.pkl', 'xgboost.pkl']
148
+
149
+ # load the selected model
150
+ model_name = model_names[model_index]
151
+
152
+ # create a radio button to select between ICA, PCA, and None
153
+ dimension_reduction = st.radio("Select a dimension reduction method", ("ICA", "PCA", "None"))
154
+
155
+ # load the selected model and the corresponding dimension reduction method
156
+
157
+ if st.button("Predict"):
158
+ if dimension_reduction == "ICA":
159
+ data = ica_to_epochs(file_path)
160
+ features_array = np.array(concatenate_fucntions(data))
161
+ model_path = "models/" + model_name[:-4] + "_ica.pkl"
162
+ elif dimension_reduction == "PCA":
163
+ data = pca_to_epochs(file_path)
164
+ features_array = np.array(concatenate_fucntions(data))
165
+ model_path = "models/" + model_name[:-4] + "_pca.pkl"
166
+ else:
167
+ data = read_data(file_path)
168
+ features_array = np.array(concatenate_fucntions(data))
169
+ model_path = "models/" + model_name
170
+
171
+ with open(model_path, 'rb') as f:
172
+ model = joblib.load(f)
173
+
174
+ dict_pred = {0: "Eyes Open", 1: "Eyes Closed", 2: "Memory Task", 3: "Music Task", 4: "Math Task"}
175
+ result = model.predict(features_array)
176
+
177
+ # data frame with features and results labels
178
+ df = pd.DataFrame(features_array)
179
+ df["predicted"] = result
180
+ # map labels to emotions
181
+ df["predicted"] = df["predicted"].map(dict_pred)
182
+
183
+ # create data frames using value_counts
184
+ df1 = df["predicted"].value_counts().rename_axis('predicted').reset_index(name='count')
185
+
186
+ st.header("Predicted Labels")
187
+ st.subheader(model_ + " with " + dimension_reduction)
188
+ st.dataframe(df1)
189
+
190
+ mode = df1["count"].idxmax()
191
+ st.write("Predicted class :", df1["predicted"][mode])
192
+
193
+
194
+ def home_page():
195
+ st.title("EEG Signal Classification")
196
+ with st.container():
197
+ st.subheader("Introduction")
198
+ st.write(
199
+ "EEG signals (electroencephalogram signals) are electrical brain signals that are recorded by placing electrodes on the scalp. These signals are generated by the electrical activity of neurons in the brain and can be used to study brain function, cognitive processes, and various neurological disorders. EEG signals are measured as voltage fluctuations over time, and can provide information about the timing, frequency, and amplitude of brain activity in different regions of the brain. EEG signals can be recorded during different states such as resting, cognitive tasks, sleep, and other activities, providing insights into the underlying neural processes.")
200
+ st.write("---")
201
+ st.subheader("Key Features")
202
+ st.write(
203
+ """
204
+ - This is a web application that classifies EEG signals into 5 classes: Eyes Open, Eyes Closed, Memory Task Music Task, and Math Task.
205
+ - The application uses a machine learning model trained on the EEG data from 100 subjects. The model is trained on features extracted from the EEG signals using ICA and PCA.
206
+ - We have trained 5 different machine learning models: Logistic Regression, KNN, Random Forest, Decision Tree, and XGBoost.
207
+ - The application allows the user to upload a .set file containing EEG data and predict the class of the EEG signal.""")
208
+ st.write("---")
209
+ st.subheader("Problem Statement")
210
+ st.write("To predict a specific outcome variable, such as sleep quality, emotion, "
211
+ "mental health, or mind-wandering tendencies based on the EEG and other measures to build a "
212
+ "supervised machine learning model that can accurately classify EEG recordings from 60 participants "
213
+ "into one of the five classes: resting with eyes closed, resting with eyes open, cognitive task of "
214
+ "subtraction, cognitive task of listening to music, and cognitive task of memory.")
215
+ st.write("---")
216
+ st.subheader("Future Scope")
217
+ st.write(
218
+ "Using EEG signals to map dopamine and addiction by allowing subjects to perform certain tasks when the mind is tired and releasing dopamine by allowing them to do dopamine releasing activities, and then performing the same tasks which they were finding difficult to before consuming drinkables/eatables which induce dopamine or performing tasks which release dopamine. By extending this research we can identify how distraction when consumed more can hamper cognitive behaviour and neural ability, and therefore we can take this research and generate certain novel insights which would aware and benefit the society.")
219
+ with st.container():
220
+ st.write("---")
221
+ st.write("##")
222
+ image_column, text_column = st.columns((1, 2))
223
+ with image_column:
224
+ st.image(sml_poster, use_column_width=True)
225
+ with text_column:
226
+ st.subheader("EEG Classification - Machine Learning")
227
+ st.write(
228
+ """
229
+ This poster explains and summarizes the project.
230
+ """
231
+ )
232
+ st.markdown(
233
+ "[Open](https://www.canva.com/design/DAFhB5pisT0/Xx_WGXhZhB6OWcUWLVNpHw/edit?utm_content=DAFhB5pisT0&utm_campaign=designshare&utm_medium=link2&utm_source=sharebutton)")
234
+
235
+ with st.container():
236
+ st.write("---")
237
+ st.write("##")
238
+ image_column, text_column = st.columns((1, 2))
239
+ with image_column:
240
+ st.image(sml_ppt, use_column_width=True)
241
+ with text_column:
242
+ st.subheader("EEG Classification - PPT")
243
+ st.write(
244
+ """
245
+ This PPT explains the overall project in brief.
246
+ """
247
+ )
248
+ link_str = "https://www.canva.com/design/DAFdMZLx4zo/LvIN87ZujuIKXT8FkFjIrA/edit?utm_content=DAFdMZLx4zo&utm_campaign=designshare&utm_medium=link2&utm_source=sharebutton"
249
+ # link_str2 = "https://drive.google.com/drive/folders/1cFb_WIXBSvzkGFMEtjxAtnz502aEXSM4?usp=sharing"
250
+ st.markdown(f"[View]({link_str})")
251
+
252
+ with st.container():
253
+ st.write("---")
254
+ st.write("##")
255
+ image_column, text_column = st.columns((1, 2))
256
+ with image_column:
257
+ st.image(dataset_img)
258
+ with text_column:
259
+ st.subheader("Dataset - OpenNeuro")
260
+ st.write(
261
+ """
262
+ The dataset includes electroencephalogram (EEG) data from 60 participants with all three recording sessions, including the present (session 1), 90 min later (session 2), and one month later (session 3). The average age of all the participants is 20.01 years old (range 18–28) and the median is 20 years old. There are 32 females and 28 males. Part of the dataset was utilized to investigate the reproducibility of power spectrum, functional connectivity and network construction in eyes-open and eyes-closed resting-state EEG, and was published in Journal of Neuroscience Methods3.
263
+ """
264
+ )
265
+ link_str = "https://openneuro.org/datasets/ds004148/versions/1.0.1"
266
+ st.markdown(f"[View]({link_str})")
267
+
268
+
269
+ # create a Streamlit app
270
+ def about_us():
271
+ st.image(about_img)
272
+
273
+
274
+ def app():
275
+ tab1, tab2, tab3 = st.tabs(["Our Project", "Model", "About us"])
276
+ with tab1:
277
+ home_page()
278
+ with tab2:
279
+ model()
280
+ with tab3:
281
+ about_us()
282
+
283
+
284
+ # run the app
285
+ if __name__ == '__main__':
286
+ app()