-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbayesOpt.py
165 lines (131 loc) · 4.66 KB
/
bayesOpt.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
import os
import timeit
import skopt
from sklearn.model_selection import cross_val_predict
from sklearn.metrics import f1_score
from sklearn.metrics import confusion_matrix
import model
import dataset
import pipeline
import scoring
import utils
import hyperparameters
from config import Configuration as config
# Build data reader and get training data
dr = dataset.DataReader()
X = dr.train
y = dr.labels
# Build pipeline
p = pipeline.Pipeline(X, y)
X = p.X
y = p.y
offsets_assoc = p.offsets_assoc
modalities_assoc = p.modalities_assoc
num_classes = config.num_classes
num_modalities = dataset.DataReader.num_modalities
batch_size = config.batch_size
num_features = p.num_features
space = hyperparameters.space
def objective(params):
kernel_sizes = dict.fromkeys(modalities_assoc['Torso'])
for i, (k, _) in enumerate(kernel_sizes.items()):
offset = (i * 3) + 2
kernel_sizes[k] = params[offset:offset+3]
estimator = model.Estimator(
num_classes=num_classes,
num_modalities=num_modalities,
fingerprint_size=num_features,
batch_size=batch_size,
learning_rate=params[0], # 0.1,
decay=10**-1,
num_filters=params[1],
kernel_sizes=kernel_sizes,
overlap=params[23],
num_units_dense_layer=params[24],
dropout=params[25],
offsets_assoc=offsets_assoc,
modalities_assoc=modalities_assoc
)
if config.VALIDATION == 'meta-segmented-cv':
print('======================================================')
print(' META-SEGMENTED CROSS-VALIDATION ')
print('======================================================')
from metacvpartition import metacvpartition
_X = X
_y = y[:, 0]
mxval = metacvpartition(
_y
, config.xval_nfolds
, config.xval_metasegmentlength
, debug=False)
y_pred = cross_val_predict(
estimator,
_X, _y,
cv=mxval.splitsGenerator(),
n_jobs=config.N_JOBS_cv,
verbose=6)
print(y_pred.shape)
conf_mat = confusion_matrix(_y, y_pred)
print(conf_mat)
f = utils.save(conf_mat, 'confusion_matrix', estimator._io._num_persistor)
print('confusion matrix saved to %s' % f)
f = utils.save(y_pred, 'y_pred', estimator._io._num_persistor)
print('y_pred saved to %s' % f)
f = utils.save(_y, 'y', estimator._io._num_persistor)
print('y saved to %s' % f)
f = utils.save(list(mxval.splitsGenerator()), 'splits', estimator._io._num_persistor)
print('Generated splits saved to %s' % f)
# compute a bunch of scores -----------
fscore_micro = f1_score(_y, y_pred, average='micro')
print('[objective] f1_score_micro = %s%%' % (fscore_micro * 100,))
fscore = scoring.Fscore(_y, y_pred, list(mxval.splitGenerator()))
avg = fscore.avg_fscore()
print('[objective] f1_score_avg = %s%%' % (avg * 100,))
prre = fscore.prre_fscore()
print('[objective] f1_score_prre = %s%%' % (prre * 100,))
tpfp = fscore.tpfp_fscore()
print('[objective] f1_score_tpfp = %s%%' % (tpfp * 100,))
return -avg
def runBayes():
""" Launch bayesian optimization in order to tune Tensorflow model's
hyperparameter
"""
print('==================================================')
print('Bayesian optimization using Gaussian processes ...')
print('Experiment version %s.%s.%s-%s-%s'
% (config.VERSION
, config.REVISION
, config.MINOR_REVISION
, config.POSITION
, config.USER))
print('==================================================')
start = timeit.default_timer() # -----------------
r = skopt.gp_minimize(
objective,
space,
n_calls=config.N_CALLS,
random_state=config.SEED,
n_jobs=config.N_JOBS_bayes,
verbose=True)
stop = timeit.default_timer() # -----------------
print('Bayesian Optimization took')
print(stop - start)
# save the model to disk
f = os.path.join(
# VERSION, # folder
# 'bayesOptResults' + MINOR_VERSION + '.' + MAJOR_VERSION + '.sav')
config.experimentsfolder,
'bayesOptResults.' \
+ config.VERSION \
+ '.' + config.REVISION \
+ '.' + config.MINOR_REVISION \
+ '-' + config.POSITION \
+ '-' + config.USER \
+ '-' + config.day_out \
+ '.sav')
skopt.dump(r, open(f, 'wb'))
print('OK')
if __name__ == '__main__':
runBayes()
# params = [50, 90, 90, 0.1, 18, 30, 0.6]
# objective(params)