-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodels.py
269 lines (230 loc) · 12.6 KB
/
models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
# -*- coding: utf-8 -*-
"""models.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1eAT4BL-xbosfCzdRMv4XmcOFa7dQLvML
"""
from tensorflow.keras.models import Model, Sequential
from tensorflow.keras.layers import Dense, Activation, Permute, Dropout
from tensorflow.keras.layers import Conv2D, MaxPooling2D, AveragePooling2D
from tensorflow.keras.layers import SeparableConv2D, DepthwiseConv2D
from tensorflow.keras.layers import BatchNormalization
from tensorflow.keras.layers import SpatialDropout2D, LSTM
from tensorflow.keras.regularizers import l1_l2
from tensorflow.keras.layers import Input, Flatten, Reshape, InputLayer
from tensorflow.keras.constraints import max_norm
from tensorflow.keras import backend as K
from tensorflow.keras import regularizers
import numpy as np
from keras.datasets import imdb
from tensorflow.keras.layers import LSTM
from keras.layers import Embedding, Dense, Reshape, Input
#embeddings, dense
from tensorflow.keras.preprocessing.sequence import pad_sequences
from keras.models import Sequential
from keras.layers import Dense, Embedding, LSTM, SpatialDropout1D
from tensorflow.keras.optimizers import Adam
#MODEL1 EEGNET
def EEGNet(nb_classes, Chans=64, Samples=128,
dropoutRate=0.5, kernLength=64, F1=8,
D=2, F2=16, norm_rate=0.25, dropoutType='Dropout'):
""" Keras Implementation of EEGNet
http://iopscience.iop.org/article/10.1088/1741-2552/aace8c/meta
Note that this implements the newest version of EEGNet and NOT the earlier
version (version v1 and v2 on arxiv). We strongly recommend using this
architecture as it performs much better and has nicer properties than
our earlier version. For example:
1. Depthwise Convolutions to learn spatial filters within a
temporal convolution. The use of the depth_multiplier option maps
exactly to the number of spatial filters learned within a temporal
filter. This matches the setup of algorithms like FBCSP which learn
spatial filters within each filter in a filter-bank. This also limits
the number of free parameters to fit when compared to a fully-connected
convolution.
2. Separable Convolutions to learn how to optimally combine spatial
filters across temporal bands. Separable Convolutions are Depthwise
Convolutions followed by (1x1) Pointwise Convolutions.
While the original paper used Dropout, we found that SpatialDropout2D
sometimes produced slightly better results for classification of ERP
signals. However, SpatialDropout2D significantly reduced performance
on the Oscillatory dataset (SMR, BCI-IV Dataset 2A). We recommend using
the default Dropout in most cases.
Assumes the input signal is sampled at 128Hz. If you want to use this model
for any other sampling rate you will need to modify the lengths of temporal
kernels and average pooling size in blocks 1 and 2 as needed (double the
kernel lengths for double the sampling rate, etc). Note that we haven't
tested the model performance with this rule so this may not work well.
The model with default parameters gives the EEGNet-8,2 model as discussed
in the paper. This model should do pretty well in general, although it is
advised to do some model searching to get optimal performance on your
particular dataset.
We set F2 = F1 * D (number of input filters = number of output filters) for
the SeparableConv2D layer. We haven't extensively tested other values of this
parameter (say, F2 < F1 * D for compressed learning, and F2 > F1 * D for
overcomplete). We believe the main parameters to focus on are F1 and D.
Inputs:
nb_classes : int, number of classes to classify
Chans, Samples : number of channels and time points in the EEG data
dropoutRate : dropout fraction
kernLength : length of temporal convolution in first layer. We found
that setting this to be half the sampling rate worked
well in practice. For the SMR dataset in particular
since the data was high-passed at 4Hz we used a kernel
length of 32.
F1, F2 : number of temporal filters (F1) and number of pointwise
filters (F2) to learn. Default: F1 = 8, F2 = F1 * D.
D : number of spatial filters to learn within each temporal
convolution. Default: D = 2
dropoutType : Either SpatialDropout2D or Dropout, passed as a string.
"""
if dropoutType == 'SpatialDropout2D':
dropoutType = SpatialDropout2D
elif dropoutType == 'Dropout':
dropoutType = Dropout
else:
raise ValueError('dropoutType must be one of SpatialDropout2D '
'or Dropout, passed as a string.')
input1 = Input(shape=(Chans, Samples, 1))
##################################################################
block1 = Conv2D(F1, (1, kernLength), padding='same',
input_shape=(Chans, Samples, 1),
use_bias=False)(input1)
block1 = BatchNormalization()(block1)
block1 = DepthwiseConv2D((Chans, 1), use_bias=False,
depth_multiplier=D,
depthwise_constraint=max_norm(1.))(block1)
block1 = BatchNormalization()(block1)
block1 = Activation('elu')(block1)
block1 = AveragePooling2D((1, 4))(block1)
block1 = dropoutType(dropoutRate)(block1)
block2 = SeparableConv2D(F2, (1, 16),
use_bias=False, padding='same')(block1)
block2 = BatchNormalization()(block2)
block2 = Activation('elu')(block2)
block2 = AveragePooling2D((1, 8))(block2)
block2 = dropoutType(dropoutRate)(block2)
flatten = Flatten(name='flatten')(block2)
dense = Dense(nb_classes, name='dense',
kernel_constraint=max_norm(norm_rate))(flatten)
softmax = Activation('softmax', name='softmax')(dense)
return Model(inputs=input1, outputs=softmax)
#MODEL2 ShallowConvNet
def square(x):
return K.square(x)
def log(x):
return K.log(K.clip(x, min_value=1e-7, max_value=10000))
def ShallowConvNet(nb_classes, Chans, Samples, dropoutRate=0.5, weight_decay=0.1,
kernel_length=50, pool_s=150, stride_s=30):
""" Keras implementation of the Shallow Convolutional Network as described
in Schirrmeister et. al. (2017), Human Brain Mapping.
Assumes the input is a 2-second EEG signal sampled at 128Hz. Note that in
the original paper, they do temporal convolutions of length 25 for EEG
data sampled at 250Hz. We instead use length 13 since the sampling rate is
roughly half of the 250Hz which the paper used. The pool_size and stride
in later layers is also approximately half of what is used in the paper.
Note that we use the max_norm constraint on all convolutional layers, as
well as the classification layer. We also change the defaults for the
BatchNormalization layer. We used this based on a personal communication
with the original authors.
ours original paper changed version
pool_size 1, 35 1, 75 1, 150
strides 1, 7 1, 15 1, 30
conv filters 1, 13 1, 25 1, 50
Note that this implementation has not been verified by the original
authors. We do note that this implementation reproduces the results in the
original paper with minor deviations.
"""
# start the model
input_main = Input((Chans, Samples, 1))
block1 = Conv2D(20, (1, kernel_length), kernel_regularizer=regularizers.l2(weight_decay),
input_shape=(Chans, Samples, 1),
kernel_constraint=max_norm(2., axis=(0, 1, 2)))(input_main)
block1 = Conv2D(20, (Chans, 1), use_bias=False, kernel_regularizer=regularizers.l2(weight_decay),
kernel_constraint=max_norm(2., axis=(0, 1, 2)))(block1)
block1 = BatchNormalization(epsilon=1e-05, momentum=0.1)(block1)
block1 = Activation(square)(block1)
block1 = AveragePooling2D(pool_size=(1, pool_s), strides=(1, stride_s))(block1)
block1 = Activation(log)(block1)
block1 = Dropout(dropoutRate)(block1)
flatten = Flatten()(block1)
dense = Dense(nb_classes, kernel_constraint=max_norm(0.5))(flatten)
softmax = Activation('softmax')(dense)
return Model(inputs=input_main, outputs=softmax)
#MODEL3 DeepConvNet
def DeepConvNet(nb_classes, Chans=64, Samples=256,
dropoutRate=0.5, weight_decay=1):
""" Keras implementation of the Deep Convolutional Network as described in
Schirrmeister et. al. (2017), Human Brain Mapping.
This implementation assumes the input is a 2-second EEG signal sampled at
128Hz, as opposed to signals sampled at 250Hz as described in the original
paper. We also perform temporal convolutions of length (1, 5) as opposed
to (1, 10) due to this sampling rate difference.
Note that we use the max_norm constraint on all convolutional layers, as
well as the classification layer. We also change the defaults for the
BatchNormalization layer. We used this based on a personal communication
with the original authors.
ours original paper changed
pool_size 1, 2 1, 3
strides 1, 2 1, 3
conv filters 1, 5 1, 10
Note that this implementation has not been verified by the original
authors.
"""
# start the model
input_main = Input((Chans, Samples, 1))
block1 = Conv2D(25, (1, 5), kernel_regularizer=regularizers.l2(weight_decay),
input_shape=(Chans, Samples, 1),
kernel_constraint=max_norm(2., axis=(0, 1, 2)))(input_main)
block1 = Conv2D(25, (Chans, 1), kernel_regularizer=regularizers.l2(weight_decay),
kernel_constraint=max_norm(2., axis=(0, 1, 2)))(block1)
block1 = BatchNormalization(epsilon=1e-05, momentum=0.1)(block1)
block1 = Activation('elu')(block1)
block1 = MaxPooling2D(pool_size=(1, 2), strides=(1, 2))(block1)
block1 = Dropout(dropoutRate)(block1)
block2 = Conv2D(50, (1, 5), kernel_regularizer=regularizers.l2(weight_decay),
kernel_constraint=max_norm(2., axis=(0, 1, 2)))(block1)
block2 = BatchNormalization(epsilon=1e-05, momentum=0.1)(block2)
block2 = Activation('elu')(block2)
block2 = MaxPooling2D(pool_size=(1, 2), strides=(1, 2))(block2)
block2 = Dropout(dropoutRate)(block2)
block3 = Conv2D(100, (1, 5), kernel_regularizer=regularizers.l2(weight_decay),
kernel_constraint=max_norm(2., axis=(0, 1, 2)))(block2)
block3 = BatchNormalization(epsilon=1e-05, momentum=0.1)(block3)
block3 = Activation('elu')(block3)
block3 = MaxPooling2D(pool_size=(1, 2), strides=(1, 2))(block3)
block3 = Dropout(dropoutRate)(block3)
block4 = Conv2D(200, (1, 5), kernel_regularizer=regularizers.l2(weight_decay),
kernel_constraint=max_norm(2., axis=(0, 1, 2)))(block3)
block4 = BatchNormalization(epsilon=1e-05, momentum=0.1)(block4)
block4 = Activation('elu')(block4)
block4 = MaxPooling2D(pool_size=(1, 2), strides=(1, 2))(block4)
block4 = Dropout(dropoutRate)(block4)
flatten = Flatten()(block4)
dense = Dense(nb_classes, kernel_constraint=max_norm(0.5))(flatten)
softmax = Activation('softmax')(dense)
return Model(inputs=input_main, outputs=softmax)
#MODEL4 CNN-LSTM
def cnnlstm(nb_classes, Chans, Samples, dropoutRate=0.5, weight_decay=1):
input1 = Input(shape=(Chans, Samples, 1))
block1 = Conv2D(50, (1, 50), padding='same', kernel_regularizer=regularizers.l2(weight_decay),
input_shape=(Chans, Samples, 1),
use_bias=False)(input1)
block1 = BatchNormalization()(block1)
block1 = DepthwiseConv2D((Chans, 1), use_bias=False, kernel_regularizer=regularizers.l2(weight_decay),
depth_multiplier=2,
depthwise_constraint=max_norm(1.))(block1)
block1 = BatchNormalization()(block1)
block1 = Activation('elu')(block1)
block1 = AveragePooling2D(pool_size=(1, 40), strides=(1, 20))(block1)
block1 = Dropout(dropoutRate)(block1)
print('block1: ', block1)
reshape1 = Input(shape=(Chans, Samples, 1))
lstm1 = LSTM(10, return_sequences=True)(reshape1)
lstm1 = Dropout(dropoutRate)(lstm1)
lstm2 = LSTM(10)(lstm1)
lstm2 = Dropout(dropoutRate)(lstm2)
dense = Dense(nb_classes, kernel_constraint=max_norm(0.5))(lstm2)
softmax = Activation('softmax')(dense)
model = Model(inputs=input1, outputs=softmax)
model.summary()
return(model)