-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathairware_hyperopt.py
326 lines (273 loc) · 15.6 KB
/
airware_hyperopt.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
import os
import json
import argparse
from data import Read_Data
from keras.layers import Reshape, merge, concatenate
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D, Conv1D, MaxPooling1D
from utils.generators import *
from keras.regularizers import l2
from keras.models import Input, Model
from keras import backend as K
from keras import optimizers
from sklearn.model_selection import train_test_split
from hyperopt import Trials, STATUS_OK, tpe
from hyperas import optim
from hyperas.distributions import uniform, choice, normal
def airware_data():
param_list = HyperParams()
gd = Read_Data.GestureData(gest_set=1)
x, y, user, input_shape, lab_enc = gd.compile_data(nfft=param_list.NFFT_VAL, overlap=param_list.OVERLAP,
brange=param_list.BRANGE, max_seconds=2.5,
keras_format=True,
plot_spectogram=False,
baseline_format=False)
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, stratify=None, random_state=234)
num_classes = len(lab_enc.classes_)
param_list.input_shape = input_shape
param_list.num_classes = num_classes
return x_train, x_test, y_train, y_test, param_list
def split_model_1(x_train, x_test, y_train, y_test, param_list):
np.random.seed(234)
l2_val = l2({{normal(param_list.L2_VAL['mu'], param_list.L2_VAL['std'])}})
image_input = Input(
shape=(param_list.input_shape[0], param_list.input_shape[1] - 2, 1), dtype='float32')
x = Reshape(target_shape=(param_list.input_shape[0], param_list.input_shape[1] - 2))(image_input)
x = Conv1D({{choice(param_list.IMG_CONV_FILTERS)}}, {{choice(param_list.IMG_CONV_SIZE)}}, padding='same',
activation='relu',
kernel_initializer={{choice(param_list.KERNEL_INITIALIZER)}}, kernel_regularizer=l2_val)(x)
x = MaxPooling1D(2)(x)
x = Conv1D({{choice(param_list.IMG_CONV_FILTERS)}}, {{choice(param_list.IMG_CONV_SIZE)}}, padding='same',
activation='relu',
kernel_initializer={{choice(param_list.KERNEL_INITIALIZER)}}, kernel_regularizer=l2_val)(x)
image_x = Flatten()(MaxPooling1D(2)(x))
ir_input = Input(shape=(param_list.input_shape[0], 2, 1), dtype='float32')
x = Reshape(target_shape=(param_list.input_shape[0], 2))(ir_input)
x = Conv1D(2, 3, padding='same', activation='relu',
kernel_initializer={{choice(param_list.KERNEL_INITIALIZER)}}, kernel_regularizer=l2_val)(x)
x = MaxPooling1D(2)(x)
x = Conv1D(2, 3, padding='same', activation='relu',
kernel_initializer={{choice(param_list.KERNEL_INITIALIZER)}}, kernel_regularizer=l2_val)(x)
ir_x = Flatten()(MaxPooling1D(2)(x))
x = concatenate([image_x, ir_x])
x = Dense({{choice(param_list.HIDDEN_UNITS)}}, activation='relu',
kernel_initializer={{choice(param_list.KERNEL_INITIALIZER)}},
kernel_regularizer=l2_val)(x)
preds = Dense(param_list.num_classes, activation='softmax',
kernel_initializer={{choice(param_list.KERNEL_INITIALIZER)}})(x)
model = Model([image_input, ir_input], preds)
rmsprop = optimizers.rmsprop(lr={{choice(param_list.LR_VAL)}})
model.compile(loss='sparse_categorical_crossentropy',
optimizer=rmsprop,
metrics=['acc'])
model.fit_generator(
create_generator([x_train[:, :, 0:-2, :], x_train[:, :, -2:, :]], y_train, batch_size=param_list.BATCH_SIZE),
steps_per_epoch=int(len(x_train) / param_list.BATCH_SIZE),
epochs={{choice(param_list.NB_EPOCHS)}}, verbose=0)
score, acc = model.evaluate_generator(
create_generator([x_test[:, :, 0:-2, :], x_test[:, :, -2:, :]], y_test, batch_size=param_list.BATCH_SIZE),
steps=len(x_test)
)
print("Test Accuracy: ", acc)
return {'loss': -acc, 'status': STATUS_OK, 'model': model}
def split_model_2(x_train, x_test, y_train, y_test, param_list):
np.random.seed(234)
l2_val = l2({{normal(param_list.L2_VAL['mu'], param_list.L2_VAL['std'])}})
image_input = Input(
shape=(param_list.input_shape[0], param_list.input_shape[1] - 2, 1), dtype='float32')
x = Reshape(target_shape=(param_list.input_shape[0], param_list.input_shape[1] - 2))(image_input)
x = Conv1D({{choice(param_list.IMG_CONV_FILTERS)}}, {{choice(param_list.IMG_CONV_SIZE)}}, padding='same',
activation='relu',
kernel_initializer={{choice(param_list.KERNEL_INITIALIZER)}}, kernel_regularizer=l2_val)(x)
x = MaxPooling1D(2)(x)
x = Conv1D({{choice(param_list.IMG_CONV_FILTERS)}}, {{choice(param_list.IMG_CONV_SIZE)}}, padding='same',
activation='relu',
kernel_initializer={{choice(param_list.KERNEL_INITIALIZER)}}, kernel_regularizer=l2_val)(x)
image_x = Flatten()(MaxPooling1D(2)(x))
ir_input = Input(shape=(param_list.input_shape[0], 2, 1), dtype='float32')
x = Reshape(target_shape=(param_list.input_shape[0], 2))(ir_input)
x = Conv1D(2, 3, padding='same', activation='relu',
kernel_initializer={{choice(param_list.KERNEL_INITIALIZER)}}, kernel_regularizer=l2_val)(x)
x = MaxPooling1D(2)(x)
x = Conv1D(2, 3, padding='same', activation='relu',
kernel_initializer={{choice(param_list.KERNEL_INITIALIZER)}}, kernel_regularizer=l2_val)(x)
ir_x = Flatten()(MaxPooling1D(2)(x))
x = concatenate([image_x, ir_x])
x = Dense({{choice(param_list.HIDDEN_UNITS)}}, activation='relu',
kernel_initializer={{choice(param_list.KERNEL_INITIALIZER)}},
kernel_regularizer=l2_val)(x)
x = Dropout({{uniform(param_list.DROPOUT_VAL['lower'], param_list.DROPOUT_VAL['upper'])}})(x)
x = Dense({{choice(param_list.HIDDEN_UNITS)}}, activation='relu',
kernel_initializer={{choice(param_list.KERNEL_INITIALIZER)}},
kernel_regularizer=l2_val)(x)
x = Dropout({{uniform(param_list.DROPOUT_VAL['lower'], param_list.DROPOUT_VAL['upper'])}})(x)
x = Dense({{choice(param_list.HIDDEN_UNITS)}}, activation='relu',
kernel_initializer={{choice(param_list.KERNEL_INITIALIZER)}},
kernel_regularizer=l2_val)(x)
x = Dropout({{uniform(param_list.DROPOUT_VAL['lower'], param_list.DROPOUT_VAL['upper'])}})(x)
preds = Dense(param_list.num_classes, activation='softmax',
kernel_initializer={{choice(param_list.KERNEL_INITIALIZER)}})(x)
model = Model([image_input, ir_input], preds)
rmsprop = optimizers.rmsprop(lr={{choice(param_list.LR_VAL)}})
model.compile(loss='sparse_categorical_crossentropy',
optimizer=rmsprop,
metrics=['accuracy'])
model.fit_generator(
create_generator([x_train[:, :, 0:-2, :], x_train[:, :, -2:, :]], y_train, batch_size=param_list.BATCH_SIZE),
steps_per_epoch=int(len(x_train) / param_list.BATCH_SIZE),
epochs={{choice(param_list.NB_EPOCHS)}}, verbose=0)
score, acc = model.evaluate_generator(
create_generator([x_test[:, :, 0:-2, :], x_test[:, :, -2:, :]], y_test, batch_size=param_list.BATCH_SIZE),
steps=len(x_test)
)
print("Test Accuracy: ", acc)
return {'loss': -acc, 'status': STATUS_OK, 'model': model}
def split_model_3(x_train, x_test, y_train, y_test, param_list):
np.random.seed(234)
l2_val = l2({{normal(param_list.L2_VAL['mu'], param_list.L2_VAL['std'])}})
image_input = Input(
shape=(param_list.input_shape[0], param_list.input_shape[1] - 2, 1), dtype='float32')
x = Reshape(target_shape=(param_list.input_shape[0], param_list.input_shape[1] - 2))(image_input)
x = Conv1D({{choice(param_list.IMG_CONV_FILTERS)}}, {{choice(param_list.IMG_CONV_SIZE)}}, padding='same',
activation='relu',
kernel_initializer={{choice(param_list.KERNEL_INITIALIZER)}}, kernel_regularizer=l2_val)(x)
x = MaxPooling1D(2)(x)
x = Conv1D({{choice(param_list.IMG_CONV_FILTERS)}}, {{choice(param_list.IMG_CONV_SIZE)}}, padding='same',
activation='relu',
kernel_initializer={{choice(param_list.KERNEL_INITIALIZER)}}, kernel_regularizer=l2_val)(x)
x = MaxPooling1D(2)(x)
x = Conv1D({{choice(param_list.IMG_CONV_FILTERS)}}, {{choice(param_list.IMG_CONV_SIZE)}}, padding='same',
activation='relu',
kernel_initializer={{choice(param_list.KERNEL_INITIALIZER)}}, kernel_regularizer=l2_val)(x)
image_x = Flatten()(MaxPooling1D(2)(x))
ir_input = Input(shape=(param_list.input_shape[0], 2, 1), dtype='float32')
x = Reshape(target_shape=(param_list.input_shape[0], 2))(ir_input)
x = Conv1D(2, 2, padding='same', activation='relu',
kernel_initializer={{choice(param_list.KERNEL_INITIALIZER)}}, kernel_regularizer=l2_val)(x)
x = MaxPooling1D(2)(x)
x = Conv1D(2, 2, padding='same', activation='relu',
kernel_initializer={{choice(param_list.KERNEL_INITIALIZER)}}, kernel_regularizer=l2_val)(x)
ir_x = Flatten()(MaxPooling1D(2)(x))
x = concatenate([image_x, ir_x])
x = Dense({{choice(param_list.HIDDEN_UNITS)}}, activation='relu',
kernel_initializer={{choice(param_list.KERNEL_INITIALIZER)}},
kernel_regularizer=l2_val)(x)
x = Dropout({{uniform(param_list.DROPOUT_VAL['lower'], param_list.DROPOUT_VAL['upper'])}})(x)
x = Dense({{choice(param_list.HIDDEN_UNITS)}}, activation='relu',
kernel_initializer={{choice(param_list.KERNEL_INITIALIZER)}},
kernel_regularizer=l2_val)(x)
x = Dropout({{uniform(param_list.DROPOUT_VAL['lower'], param_list.DROPOUT_VAL['upper'])}})(x)
x = Dense({{choice(param_list.HIDDEN_UNITS)}}, activation='relu',
kernel_initializer={{choice(param_list.KERNEL_INITIALIZER)}},
kernel_regularizer=l2_val)(x)
x = Dropout({{uniform(param_list.DROPOUT_VAL['lower'], param_list.DROPOUT_VAL['upper'])}})(x)
preds = Dense(param_list.num_classes, activation='softmax',
kernel_initializer={{choice(param_list.KERNEL_INITIALIZER)}})(x)
model = Model([image_input, ir_input], preds)
rmsprop = optimizers.rmsprop(lr={{choice(param_list.LR_VAL)}})
model.compile(loss='sparse_categorical_crossentropy',
optimizer=rmsprop,
metrics=['acc'])
model.fit_generator(
create_generator([x_train[:, :, 0:-2, :], x_train[:, :, -2:, :]], y_train, batch_size=param_list.BATCH_SIZE),
steps_per_epoch=int(len(x_train) / param_list.BATCH_SIZE),
epochs={{choice(param_list.NB_EPOCHS)}}, verbose=0)
score, acc = model.evaluate_generator(
create_generator([x_test[:, :, 0:-2, :], x_test[:, :, -2:, :]], y_test, batch_size=param_list.BATCH_SIZE),
steps=len(x_test)
)
print("Test Accuracy: ", acc)
return {'loss': -acc, 'status': STATUS_OK, 'model': model}
def split_model_4(x_train, x_test, y_train, y_test, param_list):
np.random.seed(234)
l2_val = l2({{normal(param_list.L2_VAL['mu'], param_list.L2_VAL['std'])}})
image_input = Input(
shape=(param_list.input_shape[0], param_list.input_shape[1] - 2, 1), dtype='float32')
x = Reshape(target_shape=(param_list.input_shape[0], param_list.input_shape[1] - 2, 1))(image_input)
x = Conv2D({{choice(param_list.IMG_CONV_FILTERS)}}, {{choice(param_list.IMG_CONV_SIZE)}}, padding='same',
activation='relu',
kernel_initializer={{choice(param_list.KERNEL_INITIALIZER)}}, kernel_regularizer=l2_val)(x)
x = MaxPooling2D(2)(x)
x = Conv2D({{choice(param_list.IMG_CONV_FILTERS)}}, {{choice(param_list.IMG_CONV_SIZE)}}, padding='same',
activation='relu',
kernel_initializer={{choice(param_list.KERNEL_INITIALIZER)}}, kernel_regularizer=l2_val)(x)
image_x = Flatten()(MaxPooling2D(2)(x))
ir_input = Input(shape=(param_list.input_shape[0], 2, 1), dtype='float32')
x = Reshape(target_shape=(param_list.input_shape[0], 2, 1))(ir_input)
x = Conv2D(2, 3, padding='same', activation='relu',
kernel_initializer={{choice(param_list.KERNEL_INITIALIZER)}}, kernel_regularizer=l2_val)(x)
x = MaxPooling2D(2)(x)
x = Conv2D(2, 3, padding='same', activation='relu',
kernel_initializer={{choice(param_list.KERNEL_INITIALIZER)}}, kernel_regularizer=l2_val)(x)
ir_x = Flatten()(MaxPooling2D(2)(x))
x = concatenate([image_x, ir_x])
x = Dense({{choice(param_list.HIDDEN_UNITS)}}, activation='relu',
kernel_initializer={{choice(param_list.KERNEL_INITIALIZER)}},
kernel_regularizer=l2_val)(x)
preds = Dense(param_list.num_classes, activation='softmax',
kernel_initializer={{choice(param_list.KERNEL_INITIALIZER)}})(x)
model = Model([image_input, ir_input], preds)
rmsprop = optimizers.rmsprop(lr={{choice(param_list.LR_VAL)}})
model.compile(loss='sparse_categorical_crossentropy',
optimizer=rmsprop,
metrics=['acc'])
model.fit_generator(
create_generator([x_train[:, :, 0:-2, :], x_train[:, :, -2:, :]], y_train, batch_size=param_list.BATCH_SIZE),
steps_per_epoch=int(len(x_train) / param_list.BATCH_SIZE),
epochs={{choice(param_list.NB_EPOCHS)}}, verbose=0)
score, acc = model.evaluate_generator(
create_generator([x_test[:, :, 0:-2, :], x_test[:, :, -2:, :]], y_test, batch_size=param_list.BATCH_SIZE),
steps=len(x_test)
)
print("Test Accuracy: ", acc)
return {'loss': -acc, 'status': STATUS_OK, 'model': model}
def hyperparam_search(model_fn, file_path):
K.clear_session()
x_train, x_test, y_train, y_test, param_list = airware_data()
functions = [create_generator, HyperParams]
best_run, best_model = optim.minimize(model=model_fn,
data=airware_data,
algo=tpe.suggest,
max_evals=100,
trials=Trials(),
functions=functions)
print("Evalutation of best performing model:")
print(best_model.evaluate([x_test[:, :, 0:-2, :], x_test[:, :, -2:, :]], y_test))
print("Best Parameters")
print(best_run)
with open(file_path + 'model_best_run.json', 'w') as fp:
json.dump(best_run, fp)
def hyper_opt_split_model_1():
f_path = "./gridSearch/split_model_1/"
if not os.path.exists(f_path):
os.makedirs(f_path)
hyperparam_search(split_model_1, f_path)
def hyper_opt_split_model_2():
f_path = "./gridSearch/split_model_2/"
if not os.path.exists(f_path):
os.makedirs(f_path)
hyperparam_search(split_model_2, f_path)
def hyper_opt_split_model_3():
f_path = "./gridSearch/split_model_3/"
if not os.path.exists(f_path):
os.makedirs(f_path)
hyperparam_search(split_model_3, f_path)
def hyper_opt_split_model_4():
f_path = "./gridSearch/split_model_4/"
if not os.path.exists(f_path):
os.makedirs(f_path)
hyperparam_search(split_model_4, f_path)
if __name__ == '__main__':
function_map = {'model_1': hyper_opt_split_model_1,
'model_2': hyper_opt_split_model_2,
'model_3': hyper_opt_split_model_3,
'model_4': hyper_opt_split_model_4}
parser = argparse.ArgumentParser(description="Hyperparameter optimization")
parser.add_argument('-model',
help="Select model",
choices=['model_1', 'model_2',
'model_3', 'model_4'])
args = parser.parse_args()
function = function_map[args.model]
print("Model:", args.model)
function()