-
Notifications
You must be signed in to change notification settings - Fork 52
/
train.py
2366 lines (1922 loc) · 85 KB
/
train.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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import numpy as np
import pandas as pd
import xgboost as xgb
import argparse
import os
import datetime
import itertools
from shutil import copy2
np.random.seed(1337)
from sklearn.metrics import mean_absolute_error
from sklearn.cross_validation import KFold, train_test_split
from sklearn.ensemble import ExtraTreesRegressor, RandomForestRegressor, GradientBoostingRegressor, AdaBoostRegressor
from sklearn.neighbors import KNeighborsRegressor
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Ridge
from sklearn.svm import SVR
from sklearn.decomposition import TruncatedSVD
from sklearn.datasets import dump_svmlight_file
from sklearn.utils import shuffle, resample
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.layers.advanced_activations import PReLU
from keras.layers.normalization import BatchNormalization
from keras.optimizers import SGD, Adam, Adadelta
from keras.callbacks import ModelCheckpoint
from keras import regularizers
from keras_util import ExponentialMovingAverage, batch_generator
from statsmodels.regression.quantile_regression import QuantReg
from pylightgbm.models import GBMRegressor
from scipy.stats import boxcox
from bayes_opt import BayesianOptimization
from util import Dataset, load_prediction, hstack
categoricals = Dataset.get_part_features('categorical')
class CategoricalAlphaEncoded(object):
requirements = ['categorical']
def __init__(self, combinations=[]):
self.combinations = [map(categoricals.index, comb) for comb in combinations]
def fit_transform(self, ds):
return self.transform(ds)
def transform(self, ds):
test_cat = ds['categorical']
test_res = np.zeros((test_cat.shape[0], len(categoricals) + len(self.combinations)), dtype=np.float32)
for col in xrange(len(categoricals)):
test_res[:, col] = self.transform_column(test_cat[:, col])
for idx, comb in enumerate(self.combinations):
col = idx + len(categoricals)
test_res[:, col] = self.transform_column(map(''.join, test_cat[:, comb]))
return test_res
def transform_column(self, arr):
def encode(charcode):
r = 0
ln = len(charcode)
for i in range(ln):
r += (ord(charcode[i])-ord('A')+1)*26**(ln-i-1)
return r
return np.array(map(encode, arr))
def get_feature_names(self):
return categoricals + ['_'.join(categoricals[c] for c in comb) for comb in self.combinations]
class CategoricalMeanEncoded(object):
requirements = ['categorical']
def __init__(self, C=100, loo=False, noisy=True, noise_std=None, random_state=11, combinations=[]):
self.random_state = np.random.RandomState(random_state)
self.C = C
self.loo = loo
self.noisy = noisy
self.noise_std = noise_std
self.combinations = [map(categoricals.index, comb) for comb in combinations]
def fit_transform(self, ds):
train_cat = ds['categorical']
train_target = pd.Series(np.log(ds['loss'] + 100))
train_res = np.zeros((train_cat.shape[0], len(categoricals) + len(self.combinations)), dtype=np.float32)
self.global_target_mean = train_target.mean()
self.global_target_std = train_target.std() if self.noise_std is None else self.noise_std
self.target_sums = {}
self.target_cnts = {}
for col in xrange(len(categoricals)):
train_res[:, col] = self.fit_transform_column(col, train_target, pd.Series(train_cat[:, col]))
for idx, comb in enumerate(self.combinations):
col = idx + len(categoricals)
train_res[:, col] = self.fit_transform_column(col, train_target, pd.Series(map(''.join, train_cat[:, comb])))
return train_res
def transform(self, ds):
test_cat = ds['categorical']
test_res = np.zeros((test_cat.shape[0], len(categoricals) + len(self.combinations)), dtype=np.float32)
for col in xrange(len(categoricals)):
test_res[:, col] = self.transform_column(col, pd.Series(test_cat[:, col]))
for idx, comb in enumerate(self.combinations):
col = idx + len(categoricals)
test_res[:, col] = self.transform_column(col, pd.Series(map(''.join, test_cat[:, comb])))
return test_res
def fit_transform_column(self, col, train_target, train_series):
self.target_sums[col] = train_target.groupby(train_series).sum()
self.target_cnts[col] = train_target.groupby(train_series).count()
if self.noisy:
train_res_reg = self.random_state.normal(
loc=self.global_target_mean * self.C,
scale=self.global_target_std * np.sqrt(self.C),
size=len(train_series)
)
else:
train_res_reg = self.global_target_mean * self.C
train_res_num = train_series.map(self.target_sums[col]) + train_res_reg
train_res_den = train_series.map(self.target_cnts[col]) + self.C
if self.loo: # Leave-one-out mode, exclude current observation
train_res_num -= train_target
train_res_den -= 1
return np.exp(train_res_num / train_res_den).values
def transform_column(self, col, test_series):
test_res_num = test_series.map(self.target_sums[col]).fillna(0.0) + self.global_target_mean * self.C
test_res_den = test_series.map(self.target_cnts[col]).fillna(0.0) + self.C
return np.exp(test_res_num / test_res_den).values
def get_feature_names(self):
return categoricals + ['_'.join(categoricals[c] for c in comb) for comb in self.combinations]
class BaseAlgo(object):
def fit_predict(self, train, val=None, test=None, **kwa):
self.fit(train[0], train[1], val[0] if val else None, val[1] if val else None, **kwa)
if val is None:
return self.predict(test[0])
else:
return self.predict(val[0]), self.predict(test[0])
class Xgb(BaseAlgo):
default_params = {
'objective': 'reg:linear',
'eval_metric': 'mae',
'silent': 1,
'nthread': -1,
}
def __init__(self, params, n_iter=400, huber=None, fair=None, fair_decay=0):
self.params = self.default_params.copy()
for k in params:
self.params[k] = params[k]
self.n_iter = n_iter
self.huber = huber
self.fair = fair
self.fair_decay = fair_decay
if self.huber is not None:
self.objective = self.huber_approx_obj
elif self.fair is not None:
self.objective = self.fair_obj
else:
self.objective = None
def fit(self, X_train, y_train, X_eval=None, y_eval=None, seed=42, feature_names=None, eval_func=None, size_mult=None, name=None):
feval = lambda y_pred, y_true: ('mae', eval_func(y_true.get_label(), y_pred))
params = self.params.copy()
params['seed'] = seed
params['base_score'] = np.median(y_train)
dtrain = xgb.DMatrix(X_train, label=y_train, feature_names=feature_names)
if X_eval is None:
watchlist = [(dtrain, 'train')]
else:
deval = xgb.DMatrix(X_eval, label=y_eval, feature_names=feature_names)
watchlist = [(deval, 'eval'), (dtrain, 'train')]
if size_mult is None:
n_iter = self.n_iter
else:
n_iter = int(self.n_iter * size_mult)
self.iter = 0
self.model = xgb.train(params, dtrain, n_iter, watchlist, self.objective, feval, verbose_eval=20)
self.model.dump_model('xgb-%s.dump' % name, with_stats=True)
self.feature_names = feature_names
print " Feature importances: %s" % ', '.join('%s: %d' % t for t in sorted(self.model.get_fscore().items(), key=lambda t: -t[1]))
def predict(self, X):
return self.model.predict(xgb.DMatrix(X, feature_names=self.feature_names))
def optimize(self, X_train, y_train, X_eval, y_eval, param_grid, eval_func=None, seed=42):
feval = lambda y_pred, y_true: ('mae', eval_func(y_true.get_label(), y_pred))
dtrain = xgb.DMatrix(X_train, label=y_train)
deval = xgb.DMatrix(X_eval, label=y_eval)
def fun(**kw):
params = self.params.copy()
params['seed'] = seed
params['base_score'] = np.median(y_train)
for k in kw:
if type(param_grid[k][0]) is int:
params[k] = int(kw[k])
else:
params[k] = kw[k]
print "Trying %s..." % str(params)
self.iter = 0
model = xgb.train(params, dtrain, 10000, [(dtrain, 'train'), (deval, 'eval')], self.objective, feval, verbose_eval=20, early_stopping_rounds=100)
print "Score %.5f at iteration %d" % (model.best_score, model.best_iteration)
return - model.best_score
opt = BayesianOptimization(fun, param_grid)
opt.maximize(n_iter=100)
print "Best mae: %.5f, params: %s" % (opt.res['max']['max_val'], opt.res['mas']['max_params'])
def huber_approx_obj(self, preds, dtrain):
d = preds - dtrain.get_label()
h = self.huber
scale = 1 + (d / h) ** 2
scale_sqrt = np.sqrt(scale)
grad = d / scale_sqrt
hess = 1 / scale / scale_sqrt
return grad, hess
def fair_obj(self, preds, dtrain):
x = preds - dtrain.get_label()
c = self.fair
den = np.abs(x) * np.exp(self.fair_decay * self.iter) + c
grad = c*x / den
hess = c*c / den ** 2
self.iter += 1
return grad, hess
class LightGBM(BaseAlgo):
default_params = {
'exec_path': 'lightgbm',
'num_threads': 4
}
def __init__(self, params):
self.params = self.default_params.copy()
for k in params:
self.params[k] = params[k]
def fit(self, X_train, y_train, X_eval=None, y_eval=None, seed=42, feature_names=None, eval_func=None, **kwa):
params = self.params.copy()
params['bagging_seed'] = seed
params['feature_fraction_seed'] = seed + 3
self.model = GBMRegressor(**params)
if X_eval is None:
self.model.fit(X_train, y_train)
else:
self.model.fit(X_train, y_train, test_data=[(X_eval, y_eval)])
def predict(self, X):
return self.model.predict(X)
class LibFM(BaseAlgo):
default_params = {
}
def __init__(self, params={}):
self.params = self.default_params.copy()
for k in params:
self.params[k] = params[k]
self.exec_path = 'libFM'
self.tmp_dir = "libfm_models/{}".format(datetime.datetime.now().strftime('%Y%m%d-%H%M'))
def __del__(self):
#if os.path.exists(self.tmp_dir):
# rmtree(self.tmp_dir)
pass
def fit(self, X_train, y_train, X_eval=None, y_eval=None, seed=42, feature_names=None, eval_func=None, **kwa):
if not os.path.exists(self.tmp_dir):
os.makedirs(self.tmp_dir)
train_file = os.path.join(self.tmp_dir, 'train.svm')
eval_file = os.path.join(self.tmp_dir, 'eval.svm')
out_file = os.path.join(self.tmp_dir, 'out.txt')
print "Exporting train..."
with open(train_file, 'w') as f:
dump_svmlight_file(*shuffle(X_train, y_train, random_state=seed), f=f)
if X_eval is None:
eval_file = train_file
else:
print "Exporting eval..."
with open(eval_file, 'w') as f:
dump_svmlight_file(X_eval, y_eval, f=f)
params = self.params.copy()
params['seed'] = seed
params['task'] = 'r'
params['train'] = train_file
params['test'] = eval_file
params['out'] = out_file
params['save_model'] = os.path.join(self.tmp_dir, 'model.libfm')
params = " ".join("-{} {}".format(k, params[k]) for k in params)
command = "{} {}".format(self.exec_path, params)
print command
os.system(command)
def predict(self, X):
train_file = os.path.join(self.tmp_dir, 'train.svm')
pred_file = os.path.join(self.tmp_dir, 'pred.svm')
out_file = os.path.join(self.tmp_dir, 'out.txt')
print "Exporting pred..."
with open(pred_file, 'w') as f:
dump_svmlight_file(X, np.zeros(X.shape[0]), f=f)
params = self.params.copy()
params['iter'] = 0
params['task'] = 'r'
params['train'] = train_file
params['test'] = pred_file
params['out'] = out_file
params['load_model'] = os.path.join(self.tmp_dir, 'model.libfm')
params = " ".join("-{} {}".format(k, params[k]) for k in params)
command = "{} {}".format(self.exec_path, params)
print command
os.system(command)
return pd.read_csv(out_file, header=None).values.flatten()
class Sklearn(BaseAlgo):
def __init__(self, model):
self.model = model
def fit(self, X_train, y_train, X_eval=None, y_eval=None, seed=42, feature_names=None, eval_func=None, **kwa):
self.model.fit(X_train, y_train)
if X_eval is not None and hasattr(self.model, 'staged_predict'):
for i, p_eval in enumerate(self.model.staged_predict(X_eval)):
print "Iter %d score: %.5f" % (i, eval_func(y_eval, p_eval))
def predict(self, X):
return self.model.predict(X)
def optimize(self, X_train, y_train, X_eval, y_eval, param_grid, eval_func, seed=42):
def fun(**params):
for k in params:
if type(param_grid[k][0]) is int:
params[k] = int(params[k])
print "Trying %s..." % str(params)
self.model.set_params(**params)
self.fit(X_train, y_train)
if hasattr(self.model, 'staged_predict'):
best_score = 1e9
best_i = -1
for i, p_eval in enumerate(self.model.staged_predict(X_eval)):
mae = eval_func(y_eval, p_eval)
if mae < best_score:
best_score = mae
best_i = i
print "Best score after %d iters: %.5f" % (best_i, best_score)
else:
p_eval = self.predict(X_eval)
best_score = eval_func(y_eval, p_eval)
print "Score: %.5f" % best_score
return -best_score
opt = BayesianOptimization(fun, param_grid)
opt.maximize(n_iter=100)
print "Best mae: %.5f, params: %s" % (opt.res['max']['max_val'], opt.res['mas']['max_params'])
class QuantileRegression(object):
def fit_predict(self, train, val=None, test=None, **kwa):
model = QuantReg(train[1], train[0]).fit(q=0.5, max_iter=10000)
if val is None:
return model.predict(test[0])
else:
return model.predict(val[0]), model.predict(test[0])
class Keras(BaseAlgo):
def __init__(self, arch, params, scale=True, loss='mae', checkpoint=False):
self.arch = arch
self.params = params
self.scale = scale
self.loss = loss
self.checkpoint = checkpoint
def fit(self, X_train, y_train, X_eval=None, y_eval=None, seed=42, feature_names=None, eval_func=None, **kwa):
params = self.params
if callable(params):
params = params()
np.random.seed(seed * 11 + 137)
if self.scale:
self.scaler = StandardScaler(with_mean=False)
X_train = self.scaler.fit_transform(X_train)
if X_eval is not None:
X_eval = self.scaler.transform(X_eval)
checkpoint_path = "/tmp/nn-weights-%d.h5" % seed
self.model = self.arch((X_train.shape[1],), params)
self.model.compile(optimizer=params.get('optimizer', 'adadelta'), loss=self.loss)
callbacks = list(params.get('callbacks', []))
if self.checkpoint:
callbacks.append(ModelCheckpoint(checkpoint_path, monitor='val_loss', save_best_only=True, verbose=0))
self.model.fit_generator(
generator=batch_generator(X_train, y_train, params['batch_size'], True), samples_per_epoch=X_train.shape[0],
validation_data=batch_generator(X_eval, y_eval, 800) if X_eval is not None else None, nb_val_samples=X_eval.shape[0] if X_eval is not None else None,
nb_epoch=params['n_epoch'], verbose=1, callbacks=callbacks)
if self.checkpoint and os.path.isfile(checkpoint_path):
self.model.load_weights(checkpoint_path)
def predict(self, X):
if self.scale:
X = self.scaler.transform(X)
return self.model.predict_generator(batch_generator(X, batch_size=800), val_samples=X.shape[0]).reshape((X.shape[0],))
def regularizer(params):
if 'l1' in params and 'l2' in params:
return regularizers.l1l2(params['l1'], params['l2'])
elif 'l1' in params:
return regularizers.l1(params['l1'])
elif 'l2' in params:
return regularizers.l2(params['l2'])
else:
return None
def nn_lr(input_shape, params):
model = Sequential()
model.add(Dense(1, input_shape=input_shape))
return model
def nn_mlp(input_shape, params):
model = Sequential()
for i, layer_size in enumerate(params['layers']):
reg = regularizer(params)
if i == 0:
model.add(Dense(layer_size, init='he_normal', W_regularizer=reg, input_shape=input_shape))
else:
model.add(Dense(layer_size, init='he_normal', W_regularizer=reg))
if params.get('batch_norm', False):
model.add(BatchNormalization())
if 'dropouts' in params:
model.add(Dropout(params['dropouts'][i]))
model.add(PReLU())
model.add(Dense(1, init='he_normal'))
return model
def nn_mlp_2(input_shape, params):
model = Sequential()
for i, layer_size in enumerate(params['layers']):
reg = regularizer(params)
if i == 0:
model.add(Dense(layer_size, init='he_normal', W_regularizer=reg, input_shape=input_shape))
else:
model.add(Dense(layer_size, init='he_normal', W_regularizer=reg))
model.add(PReLU())
if params.get('batch_norm', False):
model.add(BatchNormalization())
if 'dropouts' in params:
model.add(Dropout(params['dropouts'][i]))
model.add(Dense(1, init='he_normal'))
return model
def load_x(ds, preset):
feature_parts = [Dataset.load_part(ds, part) for part in preset.get('features', [])]
prediction_parts = [load_prediction(ds, p, mode=preset.get('predictions_mode', 'fulltrain')) for p in preset.get('predictions', [])]
prediction_parts = [p.clip(lower=0.1).values.reshape((p.shape[0], 1)) for p in prediction_parts]
if 'prediction_transform' in preset:
prediction_parts = map(preset['prediction_transform'], prediction_parts)
return hstack(feature_parts + prediction_parts)
def extract_feature_names(preset):
x = []
for part in preset.get('features', []):
x += Dataset.get_part_features(part)
lp = 1
for pred in preset.get('predictions', []):
if type(pred) is list:
x.append('pred_%d' % lp)
lp += 1
else:
x.append(pred)
return x
def add_powers(x, feature_names, powers):
res_feature_names = list(feature_names)
res = [x]
for p in powers:
res.append(x ** p)
for f in feature_names:
res_feature_names.append("%s^%s" % (f, str(p)))
return hstack(res), res_feature_names
norm_y_lambda = 0.7
def norm_y(y):
return boxcox(np.log1p(y), lmbda=norm_y_lambda)
def norm_y_inv(y_bc):
return np.expm1((y_bc * norm_y_lambda + 1)**(1/norm_y_lambda))
y_norm = (norm_y, norm_y_inv)
y_log = (np.log, np.exp)
def y_log_ofs(ofs):
def transform(y):
return np.log(y + ofs)
def inv_transform(yl):
return np.clip(np.exp(yl) - ofs, 1.0, np.inf)
return transform, inv_transform
def y_pow(p):
def transform(y):
return y ** p
def inv_transform(y):
return y ** (1 / p)
return transform, inv_transform
def y_pow_ofs(p, ofs):
def transform(y):
return (y + ofs) ** p
def inv_transform(y):
return np.clip(y ** (1 / p) - ofs, 1.0, np.inf)
return transform, inv_transform
## Main part
parser = argparse.ArgumentParser(description='Train model')
parser.add_argument('preset', type=str, help='model preset (features and hyperparams)')
parser.add_argument('--optimize', action='store_true', help='optimize model params')
parser.add_argument('--fold', type=int, help='specify fold')
parser.add_argument('--threads', type=int, default=4, help='specify thread count')
args = parser.parse_args()
Xgb.default_params['nthread'] = args.threads
LightGBM.default_params['num_threads'] = args.threads
n_folds = 8
l1_predictions = [
'20161204-2003-lr-ce-1278.84184',
'20161204-2029-lr-cd-1237.43406',
'20161204-2357-lr-cd-2-1256.45156',
'20161204-2047-lr-svd-1237.79692',
'20161204-2128-lr-cd-nr-1237.32174',
'20161204-2048-lr-svd-clrbf-1210.53687',
'20161204-2130-lr-svd-clrbf-2-1202.70592',
'20161204-2359-lr-svd-clrbf-3-1212.10956',
'20161207-0538-et-ce-1207.07344',
'20161207-0601-et-ce-2-1204.68542',
'20161207-0618-et-ce-3-1199.82233',
'20161207-0030-et-ce-4-1194.75138',
'20161207-0309-rf-ce-2-1193.61802',
'20161206-2200-rf-ce-3-1190.27838',
'20161207-0257-rf-ce-4-1186.23675',
'20161207-1041-rf-ce-rot-1-1236.84994',
'20161205-0006-gb-ce-1151.11060',
'20161207-1643-knn1-1370.65015',
'20161207-2025-knn2-1364.78537',
'20161208-0022-svr1-1224.28418',
'20161210-1914-nn-cd-2-1134.92794',
'20161210-1651-nn-cd-3-1132.48048',
'20161206-2201-nn-cd-4-1132.05160',
'20161210-1142-nn-cd-clrbf-1132.71487',
'20161207-1509-nn-cd-clrbf-2-1131.72969',
'20161209-1459-nn-cd-clrbf-3-1132.49145',
'20161127-2119-nn-cd-clrbf-4-1136.33283',#
'20161209-0136-nn-cd-clrbf-5-1131.69357',
'20161201-0719-nn-cd-clrbf-6-1145.02510',#
'20161211-0636-nn-cd-clrbf-7-1133.32506',
'20161207-0622-nn-svd-cd-clrbf-1-1130.29286',
'20161201-2010-nn-svd-cd-clrbf-2-1135.79176',#
'20161206-1656-nn-svd-cd-clrbf-3-1132.02805',
'20161211-0413-lgb-cd-1-1133.89988',
'20161207-2034-lgb-cd-2-1131.65831',
'20161209-1932-lgb-ce-1-1129.07923',
'20161206-1926-lgb-ce-2-1127.68636',
'20161209-0939-xgb-ce-2-1133.00048',
'20161208-1351-xgb-ce-3-1132.08820',
'20161209-1442-xgbf-ce-2-1133.85036',
'20161209-1109-xgbf-ce-3-1128.63753',
'20161208-1109-xgbf-ce-4-1128.84209',
'20161208-2307-xgbf-ce-4-2-1126.89842',
'20161204-1303-xgbf-ce-5-1131.40964',
'20161205-1313-xgbf-ce-6-1128.77616',
'20161206-1400-xgbf-ce-7-1126.68014',
'20161207-0946-xgbf-ce-8-1124.33319',
'20161204-1025-xgbf-ce-9-1123.42983',
'20161207-2128-xgbf-ce-10-1125.78132',
'20161206-0327-xgbf-ce-12-1138.85463',
'20161207-0954-xgbf-ce-13-1122.64977',
'20161210-0733-xgbf-ce-14-1125.56181',
'20161209-0336-xgbf-ce-clrbf-1-1151.51483',
'20161204-2046-xgbf-ce-clrbf-2-1139.21753',
'20161205-0123-libfm-cd-1196.11333',
'20161205-1342-libfm-svd-1177.69251',
]
l2_predictions = [
([
'20161209-2249-l2-knn-1128.69039',
'20161209-2321-l2-svd-knn-1128.60543',
'20161203-0232-l2-knn-1128.52203',
'20161203-0135-l2-svd-knn-1128.44971',
'20161130-0230-l2-svd-svr-1128.15513',
], {'power': 1.05}),
([
'20161210-2219-l2-lr-1119.94373',
'20161210-2219-l2-lr-2-1118.49848',
'20161210-2220-l2-lr-3-1118.45564',
], {'power': 1.03}),
[
'20161205-0025-l2-qr-1117.03435',
'20161207-0053-l2-qr-1116.97884',
'20161209-1948-l2-qr-1116.63408',
],
[
'20161209-2101-l2-gb-1117.93768',
'20161202-0020-l2-gb-1118.40560',
'20161211-1858-l2-gb-1117.60834',
'20161211-2153-l2-gb-2-1117.41247',
],
([
'20161125-0753-l2-xgbf-1119.04996',
'20161130-0258-l2-xgbf-1118.96658', #
'20161202-0702-l2-xgbf-1118.63437', #
'20161203-0636-l2-xgbf-1118.58470', #
'20161210-0712-l2-xgbf-1118.33470',
], {'power': 1.02}),
([
'20161202-1724-l2-xgbf-2-1118.43083',
'20161210-1952-l2-xgbf-2-1118.15322',
'20161130-2133-l2-xgbf-3-1118.75364', #
'20161203-1336-l2-xgbf-3-1118.46005', #
'20161211-0607-l2-xgbf-3-1118.16984',
], {'power': 1.02}),
[
'20161129-1219-l2-nn-1117.84214', #
'20161202-0157-l2-nn-1117.33963', #
'20161205-0337-l2-nn-1117.09224',
'20161208-0126-l2-nn-1117.15231',
'20161209-1814-l2-nn-1117.10987',
],
[
'20161124-1430-l2-nn-2-1117.28245', #
'20161125-0958-l2-nn-2-1117.29028', #
'20161129-1021-l2-nn-2-1117.39540', #
'20161129-2228-l2-nn-2-1117.01003', #
'20161202-0007-l2-nn-2-1116.65633', #
'20161207-2324-l2-nn-2-1116.84297',
],
[
'20161210-0302-l2-nn-3-1116.53105',
'20161212-1230-l2-nn-3-1116.40752',
'20161208-1708-l2-nn-5-1116.86086',
'20161210-0624-l2-nn-5-1116.83111',
'20161211-1757-l2-nn-6-1116.60009',
],
[
'20161211-1956-l2-xgbf-4-1118.39030',
'20161212-0519-l2-xgbf-4-2-1118.44814',
'20161212-1552-l2-xgbf-4-3-1118.46351',
'20161212-0959-l2-xgbf-5-1118.80387',
'20161212-1950-l2-xgbf-5-2-1118.46393',
]
]
presets = {
'xgb-tst': {
'features': ['numeric'],
'model': Xgb({'max_depth': 5, 'eta': 0.05}, n_iter=10),
'param_grid': {'colsample_bytree': [0.2, 1.0]},
},
'xgb2': {
'features': ['numeric', 'categorical_counts'],
'y_transform': y_norm,
'model': Xgb({
'max_depth': 7,
'eta': 0.1,
'colsample_bytree': 0.5,
'subsample': 0.95,
'min_child_weight': 5,
}, n_iter=400),
'param_grid': {'colsample_bytree': [0.2, 1.0]},
},
'xgb-ce': {
'features': ['numeric', 'categorical_encoded'],
'y_transform': y_norm,
'n_bags': 2,
'model': Xgb({
'max_depth': 7,
'eta': 0.03,
'colsample_bytree': 0.4,
'subsample': 0.95,
'min_child_weight': 2,
'gamma': 0.2,
}, n_iter=2000),
},
'xgb-ce-2': {
'features': ['numeric', 'categorical_encoded'],
'y_transform': y_log_ofs(200),
'n_bags': 4,
'model': Xgb({
'max_depth': 12,
'eta': 0.01,
'colsample_bytree': 0.5,
'subsample': 0.8,
'gamma': 1,
'alpha': 1,
}, n_iter=3000),
},
'xgb-ce-3': {
'features': ['numeric', 'categorical_encoded'],
'y_transform': y_log_ofs(200),
'n_bags': 4,
'model': Xgb({
'max_depth': 14,
'eta': 0.01,
'colsample_bytree': 0.5,
'subsample': 0.8,
'gamma': 1.5,
'alpha': 1,
}, n_iter=3000),
},
'xgb-ce-tst': {
'features': ['numeric', 'categorical_encoded'],
'y_transform': y_log_ofs(200),
'n_bags': 2,
'model': Xgb({
'max_depth': 14,
'eta': 0.01,
'colsample_bytree': 0.5,
'subsample': 0.8,
'gamma': 1.5,
'alpha': 1,
}, n_iter=3000),
},
'xgb4': {
'features': ['numeric', 'categorical_dummy'],
'y_transform': y_norm,
'model': Xgb({
'max_depth': 7,
'eta': 0.02,
'colsample_bytree': 0.4,
'subsample': 0.95,
'min_child_weight': 2,
}, n_iter=3000),
},
'xgb6': {
'features': ['numeric', 'categorical_encoded'],
'y_transform': y_norm,
'model': Xgb({
'max_depth': 7,
'eta': 0.03,
'colsample_bytree': 0.4,
'subsample': 0.95,
'min_child_weight': 4,
}, n_iter=2000),
'param_grid': {'max_depth': [6, 7, 8], 'min_child_weight': [3, 4, 5]},
},
'xgb7': {
'features': ['numeric'],
'feature_builders': [CategoricalMeanEncoded(C=10000, noisy=False, loo=False)],
'y_transform': y_norm,
'model': Xgb({
'max_depth': 7,
'eta': 0.03,
'colsample_bytree': 0.4,
'subsample': 0.95,
'min_child_weight': 4,
}, n_iter=2000),
'param_grid': {'max_depth': [6, 7, 8], 'min_child_weight': [3, 4, 5]},
},
'xgbh-ce': {
'features': ['numeric', 'categorical_encoded'],
#'n_bags': 2,
'model': Xgb({
'max_depth': 7,
'eta': 0.05,
'colsample_bytree': 0.4,
'subsample': 0.95,
'min_child_weight': 4,
}, n_iter=2000, huber=100),
'param_grid': {'max_depth': [6, 7, 8], 'min_child_weight': [3, 4, 5]},
},
'xgbf-ce': {
'features': ['numeric', 'categorical_encoded'],
'y_transform': y_norm,
#'n_bags': 3,
'model': Xgb({
'max_depth': 7,
'eta': 0.05,
'colsample_bytree': 0.4,
'subsample': 0.95,
'min_child_weight': 4,
'alpha': 0.0005,
}, n_iter=1100, fair=1),
'param_grid': {'max_depth': [6, 7, 8], 'min_child_weight': [3, 4, 5]},
},
'xgbf-ce-2': {
'features': ['numeric', 'categorical_encoded'],
'y_transform': y_norm,
'n_bags': 2,
'model': Xgb({
'max_depth': 8,
'eta': 0.04,
'colsample_bytree': 0.4,
'subsample': 0.95,
'gamma': 0.45,
'alpha': 0.0005,
}, n_iter=1320, fair=1),
'param_grid': {'max_depth': [6, 7, 8], 'min_child_weight': [3, 4, 5]},
},
'xgbf-ce-3': {
'features': ['numeric', 'categorical_encoded'],
'y_transform': y_norm,
'n_bags': 4,
'model': Xgb({
'max_depth': 12,
'eta': 0.02,
'colsample_bytree': 0.4,
'subsample': 0.95,
'gamma': 0.5,
'alpha': 0.5,