-
Notifications
You must be signed in to change notification settings - Fork 98
/
sklearn.py
4218 lines (3953 loc) · 162 KB
/
sklearn.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
"""
Sklearn dependent models
Decision Tree, Elastic Net, Random Forest, MLPRegressor, KNN, Adaboost
"""
import hashlib
import datetime
import random
import numpy as np
import pandas as pd
# because this attempts to make sklearn optional for overall usage
try:
from sklearn import config_context
from sklearn.multioutput import MultiOutputRegressor, RegressorChain
except Exception:
pass
from autots.models.base import ModelObject, PredictionObject
from autots.tools.probabilistic import Point_to_Probability
from autots.tools.seasonal import date_part, seasonal_int, random_datepart
from autots.tools.window_functions import window_maker, last_window, sliding_window_view
from autots.tools.cointegration import coint_johansen, btcd_decompose
from autots.tools.holiday import holiday_flag
from autots.tools.shaping import infer_frequency
# scipy is technically optional but most likely is present
try:
from scipy.stats import norm
except Exception:
class norm(object):
@staticmethod
def ppf(x):
return 1.95996398454
# norm.ppf((1 + 0.95) / 2)
def rolling_x_regressor(
df,
mean_rolling_periods: int = 30,
macd_periods: int = None,
std_rolling_periods: int = 7,
max_rolling_periods: int = None,
min_rolling_periods: int = None,
quantile90_rolling_periods: int = None,
quantile10_rolling_periods: int = None,
ewm_alpha: float = 0.5,
ewm_var_alpha: float = None,
additional_lag_periods: int = 7,
abs_energy: bool = False,
rolling_autocorr_periods: int = None,
nonzero_last_n: int = None,
add_date_part: str = None,
holiday: bool = False,
holiday_country: str = 'US',
polynomial_degree: int = None,
window: int = None,
cointegration: str = None,
cointegration_lag: int = 1,
):
"""
Generate more features from initial time series.
macd_periods ignored if mean_rolling is None.
Returns a dataframe of statistical features. Will need to be shifted by 1 or more to match Y for forecast.
so for the index date of the output here, this represents the time of the prediction being made, NOT the target datetime.
the datepart components should then represent the NEXT period ahead, which ARE the target datetime
"""
# making this all or partially Numpy (if possible) would probably be faster
local_df = df.copy()
inferred_freq = infer_frequency(local_df.index)
local_df.columns = [str(x) for x in range(len(df.columns))]
X = [local_df.rename(columns=lambda x: "lastvalue_" + x)]
if str(mean_rolling_periods).isdigit():
temp = local_df.rolling(int(mean_rolling_periods), min_periods=1).median()
# temp.columns = ['rollingmean' for col in temp.columns]
X.append(temp)
if str(macd_periods).isdigit():
temp = local_df.rolling(int(macd_periods), min_periods=1).median() - temp
temp.columns = ['macd' for col in temp.columns]
X.append(temp)
if str(std_rolling_periods).isdigit():
X.append(local_df.rolling(std_rolling_periods, min_periods=1).std())
if str(max_rolling_periods).isdigit():
X.append(local_df.rolling(max_rolling_periods, min_periods=1).max())
if str(min_rolling_periods).isdigit():
X.append(local_df.rolling(min_rolling_periods, min_periods=1).min())
if str(quantile90_rolling_periods).isdigit():
X.append(
local_df.rolling(quantile90_rolling_periods, min_periods=1).quantile(0.9)
)
if str(quantile10_rolling_periods).isdigit():
X.append(
local_df.rolling(quantile10_rolling_periods, min_periods=1).quantile(0.1)
)
if str(ewm_alpha).replace('.', '').isdigit():
ewm_df = local_df.ewm(alpha=ewm_alpha, ignore_na=True, min_periods=1).mean()
ewm_df.columns = ["ewm_alpha" for col in local_df.columns]
X.append(ewm_df)
if str(ewm_var_alpha).replace('.', '').isdigit():
X.append(local_df.ewm(alpha=ewm_var_alpha, ignore_na=True, min_periods=1).var())
if str(additional_lag_periods).isdigit():
X.append(local_df.shift(additional_lag_periods))
if nonzero_last_n is not None:
full_index = local_df.index.union(
local_df.index.shift(-nonzero_last_n, freq=inferred_freq)
)
X.append(
(local_df.reindex(full_index).bfill() != 0)
.rolling(nonzero_last_n, min_periods=1)
.sum()
.reindex(local_df.index)
)
if cointegration is not None:
if str(cointegration).lower() == "btcd":
X.append(
pd.DataFrame(
np.matmul(
btcd_decompose(
local_df.values,
retrieve_regressor(
regression_model={
"model": 'LinearRegression',
"model_params": {},
},
verbose=0,
verbose_bool=False,
random_seed=2020,
multioutput=False,
),
max_lag=cointegration_lag,
),
(local_df.values).T,
).T,
index=local_df.index,
)
)
else:
X.append(
pd.DataFrame(
np.matmul(
coint_johansen(local_df.values, k_ar_diff=cointegration_lag),
(local_df.values).T,
).T,
index=local_df.index,
)
)
if abs_energy:
X.append(local_df.pow(other=([2] * len(local_df.columns))).cumsum())
if str(rolling_autocorr_periods).isdigit():
temp = local_df.rolling(rolling_autocorr_periods).apply(
lambda x: x.autocorr(), raw=False
)
temp.columns = ['rollautocorr' for col in temp.columns]
X.append(temp)
# unlike the others, this pulls the entire window, not just one lag
if str(window).isdigit():
# we already have lag 1 using this
for curr_shift in range(1, window):
X.append(
local_df.shift(curr_shift).rename(
columns=lambda x: "window_" + str(curr_shift) + "_" + x
)
) # backfill should fill last values safely
if add_date_part not in [None, "None", "none"]:
ahead_index = local_df.index.shift(1, freq=inferred_freq)
date_part_df = date_part(ahead_index, method=add_date_part)
date_part_df.index = local_df.index
X.append(date_part_df)
X = pd.concat(X, axis=1)
if holiday:
ahead_index = local_df.index.shift(1, freq=inferred_freq)
ahead_2_index = local_df.index.shift(2, freq=inferred_freq)
full_index = ahead_index.union(ahead_2_index)
hldflag = holiday_flag(full_index, country=holiday_country)
X['holiday_flag_'] = hldflag.reindex(ahead_index).to_numpy()
X['holiday_flag_future_'] = hldflag.reindex(ahead_2_index).to_numpy()
# X = X.replace([np.inf, -np.inf], np.nan)
X = X.bfill()
if str(polynomial_degree).isdigit():
polynomial_degree = abs(int(polynomial_degree))
from sklearn.preprocessing import PolynomialFeatures
poly = PolynomialFeatures(polynomial_degree)
X = pd.DataFrame(poly.fit_transform(X))
# rename to remove duplicates but still keep names if present
X.columns = [
m + "_" + str(n)
for m, n in zip([str(x) for x in range(len(X.columns))], X.columns.tolist())
]
return X
def rolling_x_regressor_regressor(
df,
mean_rolling_periods: int = 30,
macd_periods: int = None,
std_rolling_periods: int = 7,
max_rolling_periods: int = None,
min_rolling_periods: int = None,
quantile90_rolling_periods: int = None,
quantile10_rolling_periods: int = None,
ewm_alpha: float = 0.5,
ewm_var_alpha: float = None,
additional_lag_periods: int = 7,
abs_energy: bool = False,
rolling_autocorr_periods: int = None,
nonzero_last_n: int = None,
add_date_part: str = None,
holiday: bool = False,
holiday_country: str = 'US',
polynomial_degree: int = None,
window: int = None,
future_regressor=None,
regressor_per_series=None,
static_regressor=None,
cointegration: str = None,
cointegration_lag: int = 1,
series_id=None,
):
"""Adds in the future_regressor."""
X = rolling_x_regressor(
df,
mean_rolling_periods=mean_rolling_periods,
macd_periods=macd_periods,
std_rolling_periods=std_rolling_periods,
max_rolling_periods=max_rolling_periods,
min_rolling_periods=min_rolling_periods,
ewm_var_alpha=ewm_var_alpha,
quantile90_rolling_periods=quantile90_rolling_periods,
quantile10_rolling_periods=quantile10_rolling_periods,
additional_lag_periods=additional_lag_periods,
ewm_alpha=ewm_alpha,
abs_energy=abs_energy,
rolling_autocorr_periods=rolling_autocorr_periods,
nonzero_last_n=nonzero_last_n,
add_date_part=add_date_part,
holiday=holiday,
holiday_country=holiday_country,
polynomial_degree=polynomial_degree,
window=window,
cointegration=cointegration,
cointegration_lag=cointegration_lag,
)
if future_regressor is not None:
X = pd.concat([X, future_regressor], axis=1)
if regressor_per_series is not None:
# this is actually wrong, merging on an index value that is off by one
X = X.merge(
regressor_per_series, left_index=True, right_index=True, how='left'
).bfill()
if static_regressor is not None:
X['series_id'] = df.columns[0]
X = X.merge(static_regressor, left_on="series_id", right_index=True, how='left')
X = X.drop(columns=['series_id'])
if series_id is not None:
hashed = (
int(hashlib.sha256(str(series_id).encode('utf-8')).hexdigest(), 16) % 10**16
)
X['series_id'] = hashed
return X
def retrieve_regressor(
regression_model: dict = {
"model": 'RandomForest',
"model_params": {
'n_estimators': 300,
'min_samples_leaf': 1,
'bootstrap': False,
},
},
verbose: int = 0,
verbose_bool: bool = False,
random_seed: int = 2020,
n_jobs: int = 1,
multioutput: bool = True,
):
"""Convert a model param dict to model object for regression frameworks."""
model_class = regression_model['model']
model_param_dict = regression_model.get("model_params", {})
if model_class == 'ElasticNet':
if multioutput:
from sklearn.linear_model import MultiTaskElasticNet
regr = MultiTaskElasticNet(
alpha=1.0, random_state=random_seed, **model_param_dict
)
else:
from sklearn.linear_model import ElasticNet
regr = ElasticNet(alpha=1.0, random_state=random_seed, **model_param_dict)
return regr
elif model_class == 'DecisionTree':
from sklearn.tree import DecisionTreeRegressor
regr = DecisionTreeRegressor(random_state=random_seed, **model_param_dict)
return regr
elif model_class == 'MLP':
from sklearn.neural_network import MLPRegressor
regr = MLPRegressor(
random_state=random_seed, verbose=verbose_bool, **model_param_dict
)
return regr
elif model_class == 'KerasRNN':
from autots.models.dnn import KerasRNN
regr = KerasRNN(verbose=verbose, random_seed=random_seed, **model_param_dict)
return regr
elif model_class == 'Transformer':
from autots.models.dnn import Transformer
regr = Transformer(verbose=verbose, random_seed=random_seed, **model_param_dict)
return regr
elif model_class == 'KNN':
from sklearn.neighbors import KNeighborsRegressor
if multioutput:
regr = MultiOutputRegressor(
KNeighborsRegressor(**model_param_dict, n_jobs=1),
n_jobs=n_jobs,
)
else:
regr = KNeighborsRegressor(**model_param_dict, n_jobs=n_jobs)
return regr
elif model_class == 'HistGradientBoost':
try:
from sklearn.experimental import enable_hist_gradient_boosting # noqa
except Exception:
pass
from sklearn.ensemble import HistGradientBoostingRegressor
if multioutput:
regr = MultiOutputRegressor(
HistGradientBoostingRegressor(
verbose=int(verbose_bool),
random_state=random_seed,
**model_param_dict,
)
)
else:
regr = HistGradientBoostingRegressor(
verbose=int(verbose_bool),
random_state=random_seed,
**model_param_dict,
)
return regr
elif model_class == 'LightGBM':
from lightgbm import LGBMRegressor
if multioutput:
return MultiOutputRegressor(
LGBMRegressor(
verbose=-1,
random_state=random_seed,
n_jobs=1,
**model_param_dict,
),
n_jobs=n_jobs,
)
else:
return LGBMRegressor(
verbose=-1,
random_state=random_seed,
n_jobs=n_jobs,
**model_param_dict,
)
elif model_class == "LightGBMRegressorChain":
from lightgbm import LGBMRegressor
regr = LGBMRegressor(
verbose=-1,
random_state=random_seed,
n_jobs=n_jobs,
**model_param_dict,
)
if multioutput:
return RegressorChain(regr)
else:
return regr
elif model_class == 'Adaboost':
from sklearn.ensemble import AdaBoostRegressor
if regression_model["model_params"]['estimator'] == 'SVR':
from sklearn.svm import LinearSVR
svc = LinearSVR(verbose=0, random_state=random_seed, max_iter=1500)
regr = AdaBoostRegressor(
estimator=svc,
n_estimators=regression_model["model_params"]['n_estimators'],
loss=regression_model["model_params"]['loss'],
learning_rate=regression_model["model_params"]['learning_rate'],
random_state=random_seed,
)
elif regression_model["model_params"]['estimator'] == 'LinReg':
from sklearn.linear_model import LinearRegression
linreg = LinearRegression()
regr = AdaBoostRegressor(
estimator=linreg,
n_estimators=regression_model["model_params"]['n_estimators'],
loss=regression_model["model_params"]['loss'],
learning_rate=regression_model["model_params"]['learning_rate'],
random_state=random_seed,
)
else:
regr = AdaBoostRegressor(random_state=random_seed, **model_param_dict)
if multioutput:
return MultiOutputRegressor(regr, n_jobs=n_jobs)
else:
return regr
elif model_class in ['xgboost', 'XGBRegressor']:
import xgboost as xgb
smaller_n_jobs = int(n_jobs / 2) if n_jobs > 3 else n_jobs
if False: # this is no longer necessary in 1.6 and beyond
regr = MultiOutputRegressor(
xgb.XGBRegressor(verbosity=0, **model_param_dict, n_jobs=1),
n_jobs=smaller_n_jobs,
)
else:
regr = xgb.XGBRegressor(
verbosity=0, **model_param_dict, n_jobs=smaller_n_jobs
)
return regr
elif model_class in ['SVM', "LinearSVR"]:
from sklearn.svm import LinearSVR
if multioutput:
regr = MultiOutputRegressor(
LinearSVR(verbose=verbose_bool, **model_param_dict),
n_jobs=n_jobs,
)
else:
regr = LinearSVR(verbose=verbose_bool, **model_param_dict)
return regr
elif model_class == 'Ridge':
from sklearn.linear_model import Ridge
return Ridge(random_state=random_seed, **model_param_dict)
elif model_class == "FastRidge":
from sklearn.linear_model import Ridge
return Ridge(alpha=1e-9, solver="cholesky", fit_intercept=False, copy_X=False)
elif model_class == 'BayesianRidge':
from sklearn.linear_model import BayesianRidge
regr = BayesianRidge(**model_param_dict)
if multioutput:
return RegressorChain(regr)
else:
return regr
elif model_class == "ExtraTrees":
from sklearn.ensemble import ExtraTreesRegressor
return ExtraTreesRegressor(
n_jobs=n_jobs, random_state=random_seed, **model_param_dict
)
elif model_class == "RadiusNeighbors":
from sklearn.neighbors import RadiusNeighborsRegressor
regr = RadiusNeighborsRegressor(n_jobs=n_jobs, **model_param_dict)
return regr
elif model_class == "PoissonRegresssion":
from sklearn.linear_model import PoissonRegressor
if multioutput:
regr = MultiOutputRegressor(
PoissonRegressor(fit_intercept=True, max_iter=200, **model_param_dict),
n_jobs=n_jobs,
)
else:
regr = PoissonRegressor(**model_param_dict)
return regr
elif model_class == 'RANSAC':
from sklearn.linear_model import RANSACRegressor
return RANSACRegressor(random_state=random_seed, **model_param_dict)
elif model_class == "LinearRegression":
from sklearn.linear_model import LinearRegression
return LinearRegression(**model_param_dict)
elif model_class == "GaussianProcessRegressor":
from sklearn.gaussian_process import GaussianProcessRegressor
kernel = model_param_dict.pop("kernel", None)
if kernel is not None:
if kernel == "DotWhite":
from sklearn.gaussian_process.kernels import DotProduct, WhiteKernel
kernel = DotProduct() + WhiteKernel()
elif kernel == "White":
from sklearn.gaussian_process.kernels import WhiteKernel
kernel = WhiteKernel()
elif kernel == "ExpSineSquared":
from sklearn.gaussian_process.kernels import ExpSineSquared
kernel = ExpSineSquared()
else:
from sklearn.gaussian_process.kernels import RBF
kernel = RBF()
return GaussianProcessRegressor(
kernel=kernel, random_state=random_seed, **model_param_dict
)
elif model_class in ["MultioutputGPR", "VectorizedMultiOutputGPR"]:
return VectorizedMultiOutputGPR(**model_param_dict)
elif model_class in ['RandomForest', 'random_forest', 'randomforest']:
regression_model['model'] = 'RandomForest'
from sklearn.ensemble import RandomForestRegressor
regr = RandomForestRegressor(
random_state=random_seed,
verbose=verbose_bool,
n_jobs=n_jobs,
**model_param_dict,
)
return regr
elif model_class in ["ElasticNetwork"]:
from autots.models.dnn import ElasticNetwork
return ElasticNetwork(
random_seed=random_seed, verbose=verbose, **model_param_dict
)
else:
raise ValueError(f"model_class {model_class} regressor not recognized")
def retrieve_classifier(
regression_model: dict = {
"model": 'RandomForest',
"model_params": {
'n_estimators': 300,
'min_samples_leaf': 1,
'bootstrap': False,
},
},
verbose: int = 0,
verbose_bool: bool = False,
random_seed: int = 2020,
n_jobs: int = 1,
multioutput: bool = True,
):
"""Convert a model param dict to model object for regression frameworks."""
model_class = regression_model.get('model', 'RandomForest')
model_param_dict = regression_model.get("model_params", {})
if model_class == "ExtraTrees":
from sklearn.ensemble import ExtraTreesClassifier
return ExtraTreesClassifier(
n_jobs=n_jobs, random_state=random_seed, **model_param_dict
)
elif model_class == 'DecisionTree':
from sklearn.tree import DecisionTreeClassifier
return DecisionTreeClassifier(random_state=random_seed, **model_param_dict)
elif model_class in ['xgboost', 'XGBClassifier']:
import xgboost as xgb
return xgb.XGBClassifier(verbosity=verbose, **model_param_dict, n_jobs=n_jobs)
elif model_class == "RandomForest":
from sklearn.ensemble import RandomForestClassifier
return RandomForestClassifier(
random_state=random_seed,
verbose=verbose_bool,
n_jobs=n_jobs,
**model_param_dict,
)
elif model_class == "KNN":
from sklearn.neighbors import KNeighborsClassifier
return KNeighborsClassifier(
n_jobs=n_jobs,
**model_param_dict,
)
elif model_class == "SGD":
from sklearn.linear_model import SGDClassifier
from sklearn.multioutput import MultiOutputClassifier
if multioutput:
return MultiOutputClassifier(
SGDClassifier(
random_state=random_seed,
verbose=verbose_bool,
n_jobs=n_jobs,
**model_param_dict,
)
)
else:
return SGDClassifier(
random_state=random_seed,
verbose=verbose_bool,
n_jobs=n_jobs,
**model_param_dict,
)
elif model_class == "GaussianNB":
from sklearn.naive_bayes import GaussianNB
if multioutput:
return MultiOutputClassifier(GaussianNB(**model_param_dict))
else:
return GaussianNB(**model_param_dict)
else:
raise ValueError(f"classifier {model_class} not a recognized option.")
# models that can more quickly handle many X/Y obs, with modest number of features
sklearn_model_dict = {
# 'RandomForest': 0.02, # crashes sometimes at scale for unclear reasons
'ElasticNet': 0.05,
'MLP': 0.05,
'DecisionTree': 0.02,
'KNN': 0.05,
'Adaboost': 0.01,
'SVM': 0.02, # was slow, LinearSVR seems much faster
'BayesianRidge': 0.05,
'xgboost': 0.05,
'KerasRNN': 0.001, # slow at scale
'Transformer': 0.001,
'HistGradientBoost': 0.03,
'LightGBM': 0.1,
'LightGBMRegressorChain': 0.03,
'ExtraTrees': 0.01,
'RadiusNeighbors': 0.02,
'PoissonRegresssion': 0.03,
'RANSAC': 0.05,
'Ridge': 0.02,
'GaussianProcessRegressor': 0.000000001, # slow
"ElasticNetwork": 0.01,
# 'MultioutputGPR': 0.0000001, # memory intensive kernel killing
}
multivariate_model_dict = {
'RandomForest': 0.02,
# 'ElasticNet': 0.05,
'MLP': 0.03,
'DecisionTree': 0.05,
'KNN': 0.05,
'Adaboost': 0.03,
'SVM': 0.01,
# 'BayesianRidge': 0.05,
'xgboost': 0.09,
# 'KerasRNN': 0.01, # too slow on big data
'HistGradientBoost': 0.03,
'LightGBM': 0.09,
'LightGBMRegressorChain': 0.03,
'ExtraTrees': 0.05,
'RadiusNeighbors': 0.02,
'PoissonRegresssion': 0.03,
'RANSAC': 0.05,
'Ridge': 0.02,
}
# these should train quickly with low dimensional X/Y, and not mind being run multiple in parallel
univariate_model_dict = {
'ElasticNet': 0.05,
'MLP': 0.05,
'DecisionTree': 0.05,
'KNN': 0.03,
'Adaboost': 0.05,
'SVM': 0.02,
'BayesianRidge': 0.03,
'HistGradientBoost': 0.02,
'LightGBM': 0.03,
'LightGBMRegressorChain': 0.01,
'ExtraTrees': 0.05,
'RadiusNeighbors': 0.05,
'RANSAC': 0.02,
}
# for high dimensionality, many-feature X, many-feature Y, but with moderate obs count
rolling_regression_dict = {
'RandomForest': 0.02,
'ElasticNet': 0.05,
'MLP': 0.05,
'DecisionTree': 0.05,
'KNN': 0.05,
'Adaboost': 0.03,
'SVM': 0.02,
'KerasRNN': 0.02,
'LightGBM': 0.09,
'LightGBMRegressorChain': 0.03,
'ExtraTrees': 0.05,
'RadiusNeighbors': 0.01,
'PoissonRegresssion': 0.03,
'RANSAC': 0.05,
'Ridge': 0.02,
}
# models where we can be sure the model isn't sharing information across multiple Y's...
no_shared_model_dict = {
'KNN': 0.1,
'Adaboost': 0.1,
'SVM': 0.01,
'xgboost': 0.1,
'LightGBM': 0.1,
'HistGradientBoost': 0.1,
'PoissonRegresssion': 0.05,
}
# these are models that are relatively fast with large multioutput Y, small n obs
datepart_model_dict: dict = {
'ElasticNet': 0.1,
'MLP': 0.05,
'DecisionTree': 0.02,
'Adaboost': 0.05,
'SVM': 0.001,
'KerasRNN': 0.01,
# 'Transformer': 0.02, # slow, kernel failed
'RadiusNeighbors': 0.1,
"ElasticNetwork": 0.05,
}
datepart_model_dict_deep = {
'RandomForest': 0.05, # crashes sometimes at scale for unclear reasons
'ElasticNet': 0.1,
'xgboost': 0.05,
'MLP': 0.05,
'DecisionTree': 0.02,
'Adaboost': 0.05,
'SVM': 0.01,
'KerasRNN': 0.02,
'Transformer': 0.02, # slow
'ExtraTrees': 0.01, # some params cause RAM crash?
'RadiusNeighbors': 0.1,
'MultioutputGPR': 0.001,
"ElasticNetwork": 0.05,
}
gpu = ['Transformer', 'KerasRNN', 'MLP', "ElasticNetwork"] # or more accurately, no dnn
gradient_boosting = {
'xgboost': 0.09,
'HistGradientBoost': 0.03,
'LightGBM': 0.09,
'LightGBMRegressorChain': 0.03,
}
# all tree based models
tree_dict = {
'DecisionTree': 1,
'RandomForest': 1,
'ExtraTrees': 1,
'LightGBM': 1,
'HistGradientBoost': 1,
'xgboost': 1,
'XGBRegressor': 1,
}
# pre-optimized model templates
xgparam3 = {
"model": 'xgboost',
"model_params": {
"booster": 'gbtree',
"colsample_bylevel": 0.54,
"learning_rate": 0.0125,
"max_depth": 11,
"min_child_weight": 0.0127203,
"n_estimators": 319,
},
}
xgparam1 = {
"model": 'xgboost',
"model_params": {
'n_estimators': 7,
'max_leaves': 4,
'min_child_weight': 2.5,
'learning_rate': 0.35,
'subsample': 0.95,
'colsample_bylevel': 0.56,
'colsample_bytree': 0.46,
'reg_alpha': 0.0016,
'reg_lambda': 5.3,
},
}
xgparam2 = {
"model": 'xgboost',
"model_params": {
"base_score": 0.5,
"booster": 'gbtree',
"colsample_bylevel": 0.692,
"learning_rate": 0.022,
"max_bin": 256,
"max_depth": 14,
"max_leaves": 0,
"min_child_weight": 0.024,
"n_estimators": 162,
},
}
lightgbmp1 = {
"model": 'LightGBM',
"model_params": {
"colsample_bytree": 0.1645,
"learning_rate": 0.0203,
"max_bin": 1023,
"min_child_samples": 16,
"n_estimators": 1794,
"num_leaves": 15,
"reg_alpha": 0.00098,
"reg_lambda": 0.686,
},
}
lightgbmp2 = {
"model": 'LightGBM',
"model_params": {
"colsample_bytree": 0.947,
"learning_rate": 0.7024,
"max_bin": 255,
"min_child_samples": 15,
"n_estimators": 5,
"num_leaves": 35,
"reg_alpha": 0.00308,
"reg_lambda": 5.182,
},
}
def generate_classifier_params(
model_dict=None,
method="default",
):
if model_dict is None:
if method == "fast":
model_dict = {
'xgboost': 0.5, # also crashes sometimes
# 'ExtraTrees': 0.2, # crashes sometimes
# 'RandomForest': 0.1,
'KNN': 1,
'SGD': 0.1,
}
else:
model_dict = {
'xgboost': 0.5,
'ExtraTrees': 0.2,
'RandomForest': 0.1,
'KNN': 1,
'SGD': 0.1,
}
regr_params = generate_regressor_params(
model_dict=model_dict,
method=method,
)
if regr_params["model"] == 'xgboost':
if "objective" in regr_params['model_params'].keys():
regr_params['model_params'].pop('objective', None)
elif regr_params["model"] == 'ExtraTrees':
regr_params['model_params']['criterion'] = 'gini'
return regr_params
def generate_regressor_params(
model_dict=None,
method="default",
):
"""Generate new parameters for input to regressor."""
# force neural networks for testing purposes
if method in ["default", 'random', 'fast']:
pass
elif method == "neuralnets":
model_dict = {
'KerasRNN': 0.05,
'Transformer': 0.05,
'MLP': 0.05,
"ElasticNetwork": 0.05,
}
method = "deep"
elif method == "gradient_boosting":
model_dict = gradient_boosting
method = "default"
elif method == "trees":
model_dict = tree_dict
method = "default"
elif method in sklearn_model_dict.keys():
model_dict = {method: sklearn_model_dict[method]}
elif model_dict is None:
model_dict = sklearn_model_dict
# used in Cassandra to remove slowest models
if method == "no_gpu":
model_dict = {x: y for (x, y) in model_dict.items() if x not in gpu}
model_list = list(model_dict.keys())
model = random.choices(model_list, list(model_dict.values()), k=1)[0]
if model in [
'xgboost',
'Adaboost',
'DecisionTree',
'LightGBM',
'LightGBMRegressorChain',
'MLP',
'KNN',
'KerasRNN',
'Transformer',
'HistGradientBoost',
'RandomForest',
'ExtraTrees',
'Ridge',
'GaussianProcessRegressor',
'MultioutputGPR',
'SVM',
"ElasticNetwork",
"ElasticNet",
]:
if model == 'Adaboost':
param_dict = {
"model": 'Adaboost',
"model_params": {
"n_estimators": random.choices([50, 100, 500], [0.7, 0.2, 0.1])[0],
"loss": random.choices(
['linear', 'square', 'exponential'], [0.8, 0.01, 0.1]
)[0],
"estimator": random.choices(
[None, 'LinReg', 'SVR'],
[0.8, 0.1, 0.0], # SVR slow and crash prone
)[0],
"learning_rate": random.choices([1, 0.5], [0.9, 0.1])[0],
},
}
elif model == 'ElasticNet':
param_dict = {
"model": 'ElasticNet',
"model_params": {
"l1_ratio": random.choices([0.5, 0.1, 0.9], [0.7, 0.2, 0.1])[0],
"fit_intercept": random.choices([True, False], [0.9, 0.1])[0],
"selection": random.choices(["cyclic", "random"], [0.8, 0.1])[0],
},
}
elif model == 'xgboost':
branch = random.choices(['p1', 'p2', 'p3', 'random'], [0.1, 0.1, 0.1, 0.7])[
0
]
if branch == 'p1':
param_dict = xgparam1
elif branch == 'p2':
param_dict = xgparam2
elif branch == 'p3':
param_dict = xgparam3
else:
objective = random.choices(
[
'count:poisson',
'reg:squarederror',
'reg:gamma',
'reg:pseudohubererror',
'reg:quantileerror',
],
[0.1, 0.6, 0.1, 0.1, 0.1],
)[0]
param_dict = {
"model": 'xgboost',
"model_params": {
"booster": random.choices(['gbtree', 'gblinear'], [0.7, 0.3])[
0
],
"objective": objective,
"max_depth": random.choices(
[6, 3, 2, 8], [0.6, 0.4, 0.2, 0.01]
)[0],
"eta": random.choices(
[1.0, 0.3, 0.01, 0.03, 0.05, 0.003],
[0.05, 0.1, 0.1, 0.1, 0.1, 0.1],
)[
0
], # aka learning_rate
"min_child_weight": random.choices(
[0.05, 0.5, 1, 2, 5, 10], [0.01, 0.05, 0.8, 0.1, 0.1, 0.1]
)[0],
"subsample": random.choices(
[1, 0.9, 0.7, 0.5], [0.9, 0.05, 0.05, 0.05]
)[0],
"colsample_bylevel": random.choices(
[1, 0.9, 0.7, 0.5], [0.4, 0.1, 0.1, 0.1]
)[0],
"reg_alpha": random.choices(
[0, 0.001, 0.05, 100], [0.9, 0.1, 0.05, 0.05]
)[0],
"reg_lambda": random.choices(
[1, 0.03, 0.11, 0.2, 5], [0.9, 0.05, 0.05, 0.05, 0.05]
)[0],
},
}
if random.choices([True, False], [0.4, 0.6])[0]:
param_dict["model_params"]["max_depth"] = random.choices(
[3, 6, 9], [0.1, 0.8, 0.1]
)[0]
if random.choices([True, False], [0.5, 0.5])[0]:
param_dict["model_params"]["n_estimators"] = random.choices(
[4, 7, 10, 20, 100, 1000],
[0.2, 0.2, 0.2, 0.2, 0.5, 0.2],
)[0]
if random.choices([True, False], [0.2, 0.8])[0]:
param_dict["model_params"]["grow_policy"] = "lossguide"
if objective == "reg:quantileerror":
param_dict['model_params']["quantile_alpha"] = 0.5
param_dict['model_params']["tree_method"] = "hist"
elif random.choices([True, False], [0.2, 0.8])[0]:
# new in 2.0 vector trees
param_dict['model_params']["multi_strategy"] = "multi_output_tree"
param_dict['model_params']["tree_method"] = "hist"