-
Notifications
You must be signed in to change notification settings - Fork 1
/
clf_nolearn_2_levels_cal.py
398 lines (316 loc) · 14.4 KB
/
clf_nolearn_2_levels_cal.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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
"""
"""
import numpy as np
from nolearn.lasagne import BatchIterator
from lasagne.layers import InputLayer, DenseLayer, DropoutLayer
from lasagne.nonlinearities import LeakyRectify, softmax
from lasagne.init import HeNormal
from lasagne.updates import adagrad
from theano import shared
from sklearn.base import BaseEstimator
from sklearn.calibration import CalibratedClassifierCV
from sklearn.preprocessing import LabelEncoder
from sklearn.cross_validation import StratifiedKFold
from classifier import logloss_mc
from clf_nolearn import Clf_nolearn, My_NeuralNet, EarlyStopping, AdjustVariable, float32
class ansi:
BLUE = '\033[94m'
GREEN = '\033[32m'
ENDC = '\033[0m'
class ClfCal(BaseEstimator):
"""
"""
def __init__(self, nn0, nn1, nn2):
super(ClfCal, self).__init__()
self.nn0 = nn0
self.nn1 = nn1
self.nn2 = nn2
def fit(self, X, y):
le = LabelEncoder()
id_123 = np.logical_or(np.logical_or(y==1, y==2),
y==3)
y0 = np.zeros(len(y), dtype=np.int32)
y0[id_123] = 1
X0 = np.copy(X)
y0 = le.fit_transform(y0).astype(np.int32)
X1 = X[id_123]
y1 = y[id_123]
y1 = le.fit_transform(y1).astype(np.int32)
X2 = X[np.logical_not(id_123)]
y2 = y[np.logical_not(id_123)]
y2 = le.fit_transform(y2).astype(np.int32)
self.nn0.fit(X0, y0)
self.nn1.fit(X1, y1, X1)
self.nn2.fit(X2, y2)
return self
def predict_proba(self, X):
y0_pred = self.nn0.predict_proba(X)
y1_pred = self.nn1.predict_proba(X)
y2_pred = self.nn2.predict_proba(X)
y_pred = np.zeros((y0_pred.shape[0], 9))
y_pred[:,0] = y0_pred[:,0]*y2_pred[:,0]
y_pred[:,1] = y0_pred[:,1]*y1_pred[:,0]
y_pred[:,2] = y0_pred[:,1]*y1_pred[:,1]
y_pred[:,3] = y0_pred[:,1]*y1_pred[:,2]
y_pred[:,4] = y0_pred[:,0]*y2_pred[:,1]
y_pred[:,5] = y0_pred[:,0]*y2_pred[:,2]
y_pred[:,6] = y0_pred[:,0]*y2_pred[:,3]
y_pred[:,7] = y0_pred[:,0]*y2_pred[:,4]
y_pred[:,8] = y0_pred[:,0]*y2_pred[:,5]
return y_pred
class Clf_nolearn_2_levels_cal(Clf_nolearn):
"""
Simple nolearn based classifier...
"""
def __init__(self, num_features=93, num_classes=9):
"""
"""
self.prefix = 'nl_2lv_cal'
self.num_features = num_features
self.num_classes = num_classes
self.layers0 = [('input', InputLayer),
('dropoutn', DropoutLayer),
('dense0', DenseLayer),
('dropout0', DropoutLayer),
('dense1', DenseLayer),
('dropout1', DropoutLayer),
('dense2', DenseLayer),
('dropout2', DropoutLayer),
('dense3', DenseLayer),
('dropout3', DropoutLayer),
('output', DenseLayer)]
self.early_stopping0 = EarlyStopping(patience=20)
self.nn0 = My_NeuralNet(layers=self.layers0,
input_shape=(None, self.num_features),
dropoutn_p=0.12,
dense0_num_units=900,
dense0_W=HeNormal(),
dense0_nonlinearity = LeakyRectify(leakiness=0.002),
dropout0_p=0.35,
dense1_num_units=600,
dense1_W=HeNormal(),
dense1_nonlinearity = LeakyRectify(leakiness=0.002),
dropout1_p=0.2,
dense2_num_units=400,
dense2_W=HeNormal(),
dense2_nonlinearity = LeakyRectify(leakiness=0.002),
dropout2_p=0.1,
dense3_num_units=300,
dense3_W=HeNormal(),
dense3_nonlinearity = LeakyRectify(leakiness=0.002),
dropout3_p=0.1,
output_num_units=2,
output_nonlinearity=softmax,
update=adagrad,
update_learning_rate=shared(float32(0.01)),
batch_iterator_train=BatchIterator(batch_size=256),
on_epoch_finished=[
AdjustVariable('update_learning_rate', start=0.01, stop=0.001),
# AdjustVariable('update_momentum', start=0.1, stop=0.0),
self.early_stopping0,
],
eval_size=0,
verbose=1,
max_epochs=36
)
self.layers1 = [('input', InputLayer),
('dropoutn', DropoutLayer),
('dense0', DenseLayer),
# ('gaussian0', GaussianNoiseLayer),
('dropout0', DropoutLayer),
('dense1', DenseLayer),
# ('gaussian1', GaussianNoiseLayer),
('dropout1', DropoutLayer),
('dense2', DenseLayer),
('dropout2', DropoutLayer),
# ('dense3', DenseLayer),
# ('dropout3', DropoutLayer),
('output', DenseLayer)]
self.early_stopping1 = EarlyStopping(patience=20)
self.nn1 = My_NeuralNet(layers=self.layers1,
input_shape=(None, self.num_features),
dropoutn_p=0.18,
dense0_num_units=900,
dense0_W=HeNormal(),
dense0_nonlinearity = LeakyRectify(leakiness=0.002),
dropout0_p=0.35,
dense1_num_units=600,
dense1_W=HeNormal(),
dense1_nonlinearity = LeakyRectify(leakiness=0.002),
dropout1_p=0.15,
dense2_num_units=400,
dense2_W=HeNormal(),
dense2_nonlinearity = LeakyRectify(leakiness=0.002),
dropout2_p=0.05,
output_num_units=3,
output_nonlinearity=softmax,
update=adagrad,
update_learning_rate=shared(float32(0.01)),
batch_iterator_train=BatchIterator(batch_size=256),
on_epoch_finished=[
AdjustVariable('update_learning_rate', start=0.01, stop=0.001),
# AdjustVariable('update_momentum', start=0.1, stop=0.0),
self.early_stopping1,
],
eval_size=0,
verbose=1,
max_epochs=60
)
self.layers2 = [('input', InputLayer),
('dropoutn', DropoutLayer),
('dense0', DenseLayer),
# ('gaussian0', GaussianNoiseLayer),
('dropout0', DropoutLayer),
('dense1', DenseLayer),
# ('gaussian1', GaussianNoiseLayer),
('dropout1', DropoutLayer),
('dense2', DenseLayer),
('dropout2', DropoutLayer),
# ('dense3', DenseLayer),
# ('dropout3', DropoutLayer),
('output', DenseLayer)]
self.early_stopping2 = EarlyStopping(patience=20)
self.nn2 = My_NeuralNet(layers=self.layers2,
input_shape=(None, self.num_features),
dropoutn_p=0.13,
dense0_num_units=900,
dense0_W=HeNormal(),
dense0_nonlinearity = LeakyRectify(leakiness=0.002),
dropout0_p=0.35,
dense1_num_units=600,
dense1_W=HeNormal(),
dense1_nonlinearity = LeakyRectify(leakiness=0.002),
dropout1_p=0.15,
dense2_num_units=400,
dense2_W=HeNormal(),
dense2_nonlinearity = LeakyRectify(leakiness=0.002),
dropout2_p=0.05,
output_num_units=6,
output_nonlinearity=softmax,
update=adagrad,
update_learning_rate=shared(float32(0.01)),
batch_iterator_train=BatchIterator(batch_size=256),
on_epoch_finished=[
AdjustVariable('update_learning_rate', start=0.01, stop=0.001),
# AdjustVariable('update_momentum', start=0.1, stop=0.0),
self.early_stopping2,
],
# eval_size=0.2,
eval_size=0,
verbose=1,
max_epochs=31
)
def train_validate(self, X_train, y_train, X_valid, y_valid):
"""
"""
le = LabelEncoder()
id_123 = np.logical_or(np.logical_or(y_train==1, y_train==2),
y_train==3)
y0 = np.zeros(len(y_train), dtype=np.int32)
y0[id_123] = 1
X0 = np.copy(X_train)
y0 = le.fit_transform(y0).astype(np.int32)
X1 = X_train[id_123]
y1 = y_train[id_123]
y1 = le.fit_transform(y1).astype(np.int32)
X2 = X_train[np.logical_not(id_123)]
y2 = y_train[np.logical_not(id_123)]
y2 = le.fit_transform(y2).astype(np.int32)
#Validation
id_123_valid = np.logical_or(np.logical_or(y_valid==1, y_valid==2),
y_valid==3)
y0_valid = np.zeros(len(y_valid), dtype=np.int32)
y0_valid[id_123_valid] = 1
X0_valid = np.copy(X_valid)
y0_valid = le.fit_transform(y0_valid).astype(np.int32)
X1_valid = X_valid[id_123_valid]
y1_valid = y_valid[id_123_valid]
y1_valid = le.fit_transform(y1_valid).astype(np.int32)
X2_valid = X_valid[np.logical_not(id_123_valid)]
y2_valid = y_valid[np.logical_not(id_123_valid)]
y2_valid = le.fit_transform(y2_valid).astype(np.int32)
self.nn0.max_epochs = 300
self.nn0.verbose=1
self.nn0.fit(X0, y0, X0_valid, y0_valid)
y0_pred = self.nn0.predict_proba(X_valid)
self.nn1.max_epochs = 300
self.nn1.verbose=1
self.nn1.fit(X1, y1, X1_valid, y1_valid)
y1_pred = self.nn1.predict_proba(X_valid)
self.nn2.max_epochs = 300
self.nn2.verbose=1
self.nn2.fit(X2, y2, X2_valid, y2_valid)
y2_pred = self.nn2.predict_proba(X_valid)
y_pred = np.zeros((y0_pred.shape[0], 9))
y_pred[:,0] = y0_pred[:,0]*y2_pred[:,0]
y_pred[:,1] = y0_pred[:,1]*y1_pred[:,0]
y_pred[:,2] = y0_pred[:,1]*y1_pred[:,1]
y_pred[:,3] = y0_pred[:,1]*y1_pred[:,2]
y_pred[:,4] = y0_pred[:,0]*y2_pred[:,1]
y_pred[:,5] = y0_pred[:,0]*y2_pred[:,2]
y_pred[:,6] = y0_pred[:,0]*y2_pred[:,3]
y_pred[:,7] = y0_pred[:,0]*y2_pred[:,4]
y_pred[:,8] = y0_pred[:,0]*y2_pred[:,5]
yp0 = y_pred
print logloss_mc(y_valid, yp0)
self.nn0.max_epochs = self.early_stopping0.best_valid_epoch
self.nn0.verbose=0
self.nn1.max_epochs = self.early_stopping1.best_valid_epoch
self.nn1.verbose=0
self.nn2.max_epochs = self.early_stopping2.best_valid_epoch
self.nn2.verbose=0
clf = ClfCal(self.nn0, self.nn1, self.nn2)
cc = CalibratedClassifierCV(base_estimator=clf, method='isotonic',
cv=StratifiedKFold(y_train, n_folds=3))
cc.fit(X_train, y_train)
yp1= cc.predict_proba(X_valid)
print 'Calibrated log-loss: %s' %(logloss_mc(y_valid, yp1))
y_pred = (yp0+yp1)/2.
print 'Mean log-loss: %s' %(logloss_mc(y_valid, y_pred))
self.cal_clf = cc
return y_pred
def train_test(self, X, y, X_test):
"""
"""
le = LabelEncoder()
id_123 = np.logical_or(np.logical_or(y==1, y==2), y==3)
y0 = np.zeros(len(y), dtype=np.int32)
y0[id_123] = 1
X0 = np.copy(X)
y0 = le.fit_transform(y0).astype(np.int32)
X1 = X[id_123]
y1 = y[id_123]
y1 = le.fit_transform(y1).astype(np.int32)
X2 = X[np.logical_not(id_123)]
y2 = y[np.logical_not(id_123)]
y2 = le.fit_transform(y2).astype(np.int32)
print 'working on nn0...'
self.nn0.max_epochs = self.early_stopping0.best_valid_epoch
self.nn0.verbose=0
self.nn0.fit(X0, y0)
y0_pred = self.nn0.predict_proba(X_test)
print 'working on nn1...'
self.nn1.max_epochs = self.early_stopping1.best_valid_epoch
self.nn1.verbose=0
self.nn1.fit(X1, y1)
y1_pred = self.nn1.predict_proba(X_test)
print 'working on nn2...'
self.nn2.max_epochs = self.early_stopping2.best_valid_epoch
self.nn2.verbose=0
self.nn2.fit(X2, y2)
y2_pred = self.nn2.predict_proba(X_test)
y_pred = np.zeros((y0_pred.shape[0], 9))
y_pred[:,0] = y0_pred[:,0]*y2_pred[:,0]
y_pred[:,1] = y0_pred[:,1]*y1_pred[:,0]
y_pred[:,2] = y0_pred[:,1]*y1_pred[:,1]
y_pred[:,3] = y0_pred[:,1]*y1_pred[:,2]
y_pred[:,4] = y0_pred[:,0]*y2_pred[:,1]
y_pred[:,5] = y0_pred[:,0]*y2_pred[:,2]
y_pred[:,6] = y0_pred[:,0]*y2_pred[:,3]
y_pred[:,7] = y0_pred[:,0]*y2_pred[:,4]
y_pred[:,8] = y0_pred[:,0]*y2_pred[:,5]
yp0 = y_pred
self.cal_clf.fit(X, y)
yp1 = self.cal_clf.predict_proba(X_test)
y_pred = (yp0 + yp1)/2.
return y_pred