generated from asreview/template-extension-new-model
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcnn_switch.py
350 lines (278 loc) · 13 KB
/
cnn_switch.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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
# Copyright 2020 The ASReview Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from os.path import isfile
from os import remove
import logging
import numpy as np
from tensorflow.python.keras.backend import reshape
from tensorflow.python.keras.layers.core import Reshape
try:
import tensorflow as tf
from tensorflow.keras.models import load_model
from tensorflow.keras.layers import Dense
from tensorflow.keras.layers import Conv1D
from tensorflow.keras.layers import MaxPool1D
from tensorflow.keras.layers import Dropout
from tensorflow.keras.layers import Flatten
from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.keras.models import Sequential
from tensorflow.keras.wrappers.scikit_learn import KerasClassifier
from tensorflow.keras import optimizers
except ImportError:
TF_AVAILABLE = False
else:
TF_AVAILABLE = True
try:
tf.logging.set_verbosity(tf.logging.ERROR)
except AttributeError:
logging.getLogger("tensorflow").setLevel(logging.ERROR)
from sklearn.naive_bayes import MultinomialNB
import optuna
from asreview.models.classifiers.base import BaseTrainClassifier
from asreview.utils import _set_class_weight
from tensorflow.keras import backend
def _check_tensorflow():
if not TF_AVAILABLE:
raise ImportError(
"Install tensorflow package (`pip install tensorflow`) to use"
" 'EmbeddingIdf'.")
class CNNSwitch(BaseTrainClassifier):
name = "CNNSwitch"
def __init__(self,
learning_rate=0.01,
epochs=60,
batch_size=32,
shuffle=True,
class_weight=30.0):
"""Initialize the 2-layer neural network model."""
super(CNNSwitch, self).__init__()
print("""
________________________________________
____________ CNN-NB Switcher ___________
________________________________________
_________________________,▄▓▓▓▓████▓▓▄__
_______________________▄▓█▓▀ ╠▓█▓
_____________________,▓█▓` ,,,»≤░░▄▓██
____________________]▓█▓▓▓██████████▓▀▀_
________________,,µ▄▓███▀╙`_____________
___________▄▄▓▓█▓▓▓▓▓▓▓██▓▄_____________
________▄▓██▀╙└ ╙▀██▄__________
______▄▓█▀└ ╙██▄________
____▄██▀ ▓█▓_______
___▓█▓ ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄, ╟█▓⌐_____
__▓█▌ ╟███████████████████ '╟█▓_____
_▓█▓ ╟███▄█▄███████▄█▄▀██▌ │▓█▓____
▐██ ╟███████████████████▌ ░╙██⌐___
╫█▌ ╙███████████████████ ░░▓█▌___
▓█▌ ░░╫█▌___
▓█▌ ,░░░▓█▌___
╟█▓ ░░░:██⌐___
_██▌ ░░░░▓█▓____
_╙██╕ ;░░░░▓██`____
__╙██▄ ,░░░░]▓█▓`_____
___└▓█▓, ;░░░░░▄▓█▀_______
_____╙▓█▓▄ ,≤░░░░░;▄▓█▀└________
_______└▀▓█▓▓▄╦;░░░░░;:▄▓▓██▀¬__________
______,▄▓▓█▓▓▓████▓▓███▓▓▓█▓▓▄__________
_____å█▀└ ╙██▓▀' ╚▀█▓________
_____╟█▄ ,≤░▄▓██ ▓█▓________
______╙▀█▓▓▓▓▓▓█▓▀.╙▓▓▓▓▓▓▓▓█▓▀_________
""")
self.learning_rate=learning_rate
self.epochs=int(epochs)
self.batch_size=int(batch_size)
self.shuffle=shuffle
self.class_weight=class_weight
self._model=None
self.verbose=0
self.iteration=1
self.input_dim=None
self.switched = False
self.delta=0.04
self.patience=15
self.n_trials = 80
self.switchpoint = 500
def fit(self, X, y):
self.X = X
self.y = y
if self.iteration < self.switchpoint:
self._model = MultinomialNB(alpha=3.822)
self._model.fit(X, y)
print("Model: Naive Bayes. Iteration: ", self.iteration)
self.iteration = self.iteration+1
elif self.iteration >= self.switchpoint:
self.switched = True
if self.iteration == self.switchpoint:
print("--------- SWITCHING MODELS ---------")
if self._model is None or X.shape[1] != self.input_dim:
self.input_dim = X.shape[1]
if self.iteration == self.switchpoint or (self.iteration%150) == 0:
self.hpotrial = 1
self.parameters = self.hpo()
keras_model = _create_network(
input_dim = self.input_dim,
nlayers=self.parameters["nlayers"],
nfilters=self.parameters["nfilters"],
learning_rate = self.learning_rate,
verbose = self.verbose)
self._model = KerasClassifier(keras_model, verbose=self.verbose)
self.earlystop = EarlyStopping(monitor='loss', mode='min', min_delta = self.delta, patience = self.patience, restore_best_weights= False)
history = self._model.fit(
self._add_dim(X),
y,
batch_size=self.batch_size,
epochs=self.epochs,
shuffle=self.shuffle,
verbose=self.verbose,
callbacks=[self.earlystop],
class_weight=_set_class_weight(self.class_weight))
print("Iteration: ", self.iteration, "Amount of epochs: ",len(history.history["loss"]))
self.iteration = self.iteration+1
def hpo(self):
def objective(trial):
nlayers = trial.suggest_int("nlayers",3,6)
nfilters = trial.suggest_int("nfilters",50,220)
self.input_dim = self.X.shape[1]
keras_model = _create_network(
input_dim = self.input_dim,
nlayers=nlayers,
nfilters = nfilters,
learning_rate = self.learning_rate,
verbose = self.verbose)
self._model = KerasClassifier(keras_model, verbose=self.verbose)
self.earlystop = EarlyStopping(monitor='loss', mode='min', min_delta = self.delta, patience = self.patience, restore_best_weights= True)
history = self._model.fit(
self._add_dim(self.X),
self.y,
batch_size=self.batch_size,
epochs=self.epochs,
shuffle=self.shuffle,
verbose=self.verbose,
callbacks=[self.earlystop],
class_weight=_set_class_weight(self.class_weight))
nepoch = len(history.history["loss"])-1
print("Hpo trial: ", self.hpotrial,"/",self.n_trials)
self.hpotrial = self.hpotrial+1
return history.history["loss"][nepoch]
print("---------------------------------------------------")
print("STARTING HYPERPARAMETER OPTIMISATION NEURAL NETWORK")
print("---------------------------------------------------")
optuna.logging.set_verbosity(0)
study = optuna.create_study()
study.optimize(objective, n_trials = self.n_trials)
self.parameters = study.best_params
print("FOUND HYPERPARAMETERS: ", self.parameters)
return self.parameters
def _add_dim(self,X):
if self.switched == True:
X = X.toarray()
X = X.reshape((X.shape[0],X.shape[1],1))
return X
def predict_proba(self, X):
if self.switched == False:
foo = self._model.predict_proba((X))
elif self.switched == True:
foo = self._model.predict_proba(self._add_dim(X))
return foo
def _create_network(input_dim,
nlayers,
nfilters,
learning_rate=0.1,
verbose=0):
def model_wrapper():
backend.clear_session()
model = Sequential()
if nlayers == 3:
#Block 1
model.add(Conv1D(input_shape = (input_dim, 1), filters = nfilters, kernel_size = 2, activation='relu'))
model.add(MaxPool1D(pool_size = 2))
model.add(Dropout(0.2))
#Block 2
model.add(Conv1D(filters = nfilters, kernel_size = 2, activation='relu'))
model.add(Dropout(0.2))
#Block 3
model.add(Conv1D(filters = nfilters, kernel_size = 2, activation='relu'))
model.add(MaxPool1D(pool_size = 2))
model.add(Dropout(0.2))
if nlayers == 4:
#Block 1
model.add(Conv1D(input_shape = (input_dim, 1), filters = nfilters, kernel_size = 2, activation='relu'))
model.add(MaxPool1D(pool_size = 2))
model.add(Dropout(0.2))
#Block 2
model.add(Conv1D(filters = nfilters, kernel_size = 2, activation='relu'))
model.add(Dropout(0.2))
#Block 3
model.add(Conv1D(filters = nfilters, kernel_size = 2, activation='relu'))
model.add(MaxPool1D(pool_size = 2))
model.add(Dropout(0.2))
#Block 4
model.add(Conv1D(filters = nfilters, kernel_size = 2, activation='relu'))
model.add(Dropout(0.2))
if nlayers == 5:
#Block 1
model.add(Conv1D(input_shape = (input_dim, 1), filters = nfilters, kernel_size = 2, activation='relu'))
model.add(MaxPool1D(pool_size = 2))
model.add(Dropout(0.2))
#Block 2
model.add(Conv1D(filters = nfilters, kernel_size = 2, activation='relu'))
model.add(Dropout(0.2))
#Block 3
model.add(Conv1D(filters = nfilters, kernel_size = 2, activation='relu'))
model.add(MaxPool1D(pool_size = 2))
model.add(Dropout(0.2))
#Block 4
model.add(Conv1D(filters = nfilters, kernel_size = 2, activation='relu'))
model.add(Dropout(0.2))
#Block 5
model.add(Conv1D(filters = nfilters, kernel_size = 2, activation='relu'))
model.add(MaxPool1D(pool_size = 2))
model.add(Dropout(0.2))
if nlayers == 6:
#Block 1
model.add(Conv1D(input_shape = (input_dim, 1), filters = nfilters, kernel_size = 2, activation='relu'))
model.add(MaxPool1D(pool_size = 2))
model.add(Dropout(0.2))
#Block 2
model.add(Conv1D(filters = nfilters, kernel_size = 2, activation='relu'))
model.add(Dropout(0.2))
#Block 3
model.add(Conv1D(filters = nfilters, kernel_size = 2, activation='relu'))
model.add(MaxPool1D(pool_size = 2))
model.add(Dropout(0.2))
#Block 4
model.add(Conv1D(filters = nfilters, kernel_size = 2, activation='relu'))
model.add(Dropout(0.2))
#Block 5
model.add(Conv1D(filters = nfilters, kernel_size = 2, activation='relu'))
model.add(MaxPool1D(pool_size = 2))
model.add(Dropout(0.2))
#Block 6
model.add(Conv1D(filters = nfilters, kernel_size = 2, activation='relu'))
model.add(Dropout(0.2))
#Block Prediction
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.4))
model.add(Dense(24, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
# Compile model
model.compile(
loss='binary_crossentropy',
optimizer=optimizers.RMSprop(learning_rate=learning_rate),
metrics=['acc'])
if verbose >= 1:
model.summary()
return model
return model_wrapper