-
Notifications
You must be signed in to change notification settings - Fork 0
/
training.py
1632 lines (1381 loc) · 66.5 KB
/
training.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
# *****************************************************************************************************************************************************
# IMPORTS
# *****************************************************************************************************************************************************
# -----------------------------------------------------------------------------------------------------------------------------------------------------
# LOGGING
# -----------------------------------------------------------------------------------------------------------------------------------------------------
import logging
logger = logging.getLogger(__name__)
# -----------------------------------------------------------------------------------------------------------------------------------------------------
# Normal Imports
# -----------------------------------------------------------------------------------------------------------------------------------------------------
from typing import * # noqa: F401 pylint: disable=wildcard-import,unused-wildcard-import
from .config import *
# from pyutilz.pythonlib import ensure_installed;ensure_installed("pandas numpy numba scikit-learn lightgbm catboost xgboost shap")
import copy
import inspect
from functools import partial
from types import SimpleNamespace
from collections import defaultdict
from timeit import default_timer as timer
from pyutilz.pythonlib import prefix_dict_elems
from pyutilz.system import ensure_dir_exists, tqdmu
from mlframe.helpers import get_model_best_iter, check_for_infinity
# -----------------------------------------------------------------------------------------------------------------------------------------------------
# Filesystem
# -----------------------------------------------------------------------------------------------------------------------------------------------------
import glob
from os.path import basename
from os.path import join, exists
from pyutilz.strings import slugify
from pyutilz.system import ensure_dir_exists
# -----------------------------------------------------------------------------------------------------------------------------------------------------
# Dimreducers
# -----------------------------------------------------------------------------------------------------------------------------------------------------
import umap
# -----------------------------------------------------------------------------------------------------------------------------------------------------
# OD
# -----------------------------------------------------------------------------------------------------------------------------------------------------
from sklearn.ensemble import IsolationForest
# -----------------------------------------------------------------------------------------------------------------------------------------------------
# Ensembling
# -----------------------------------------------------------------------------------------------------------------------------------------------------
from mlframe.ensembling import ensemble_probabilistic_predictions, score_ensemble, compare_ensembles
# -----------------------------------------------------------------------------------------------------------------------------------------------------
# FE
# -----------------------------------------------------------------------------------------------------------------------------------------------------
from mlframe.feature_engineering.basic import create_date_features
from mlframe.feature_engineering.timeseries import create_aggregated_features
from mlframe.feature_engineering.numerical import (
compute_simple_stats_numba,
get_simple_stats_names,
compute_numaggs,
get_numaggs_names,
compute_numaggs_parallel,
)
from mlframe.feature_engineering.categorical import compute_countaggs, get_countaggs_names
# -----------------------------------------------------------------------------------------------------------------------------------------------------
# Base classes
# -----------------------------------------------------------------------------------------------------------------------------------------------------
from abc import ABC
from sklearn.base import ClassifierMixin, RegressorMixin, TransformerMixin, is_classifier
# -----------------------------------------------------------------------------------------------------------------------------------------------------
# Plotting
# -----------------------------------------------------------------------------------------------------------------------------------------------------
import seaborn as sns
import plotly.express as px
import plotly.graph_objects as go
import matplotlib.pyplot as plt
from IPython.display import display
# -----------------------------------------------------------------------------------------------------------------------------------------------------
# IPython
# -----------------------------------------------------------------------------------------------------------------------------------------------------
from IPython.display import display
# -----------------------------------------------------------------------------------------------------------------------------------------------------
# Pandas
# -----------------------------------------------------------------------------------------------------------------------------------------------------
import pandas as pd, numpy as np, polars as pl
from pyutilz.pandaslib import get_df_memory_consumption, showcase_df_columns
from pyutilz.pandaslib import ensure_dataframe_float32_convertability, optimize_dtypes, remove_constant_columns, convert_float64_to_float32
# -----------------------------------------------------------------------------------------------------------------------------------------------------
# Hi perf & parallel
# -----------------------------------------------------------------------------------------------------------------------------------------------------
from pyutilz.system import clean_ram
import numba
from numba import njit, prange
from numba.cuda import is_available as is_cuda_available
import psutil
import dill
import joblib
from joblib import delayed, Parallel
from pyutilz.parallel import distribute_work, parallel_run
# -----------------------------------------------------------------------------------------------------------------------------------------------------
# Curated models
# -----------------------------------------------------------------------------------------------------------------------------------------------------
import lightgbm as lgb
from lightgbm import LGBMClassifier, LGBMRegressor
from catboost import CatBoostRegressor, CatBoostClassifier
from xgboost import XGBClassifier, XGBRegressor, DMatrix, QuantileDMatrix
from sklearn.ensemble import RandomForestClassifier
from sklearn.dummy import DummyClassifier, DummyRegressor
from sklearn.linear_model import LogisticRegression
from sklearn.neural_network import MLPRegressor, MLPClassifier
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.neighbors import KNeighborsRegressor, KNeighborsClassifier
from sklearn.linear_model import LinearRegression, RANSACRegressor, HuberRegressor
from sklearn.ensemble import HistGradientBoostingRegressor, GradientBoostingRegressor, RandomForestRegressor, ExtraTreesRegressor
from sklearn.ensemble import HistGradientBoostingClassifier, GradientBoostingClassifier, RandomForestClassifier, ExtraTreesClassifier
# -----------------------------------------------------------------------------------------------------------------------------------------------------
# FS
# -----------------------------------------------------------------------------------------------------------------------------------------------------
from mlframe.feature_selection.wrappers import RFECV, VotesAggregation, OptimumSearch
from mlframe.feature_selection.filters import MRMR
from optbinning import BinningProcess
# -----------------------------------------------------------------------------------------------------------------------------------------------------
# Cats
# -----------------------------------------------------------------------------------------------------------------------------------------------------
import category_encoders as ce
# -----------------------------------------------------------------------------------------------------------------------------------------------------
# Splitters
# -----------------------------------------------------------------------------------------------------------------------------------------------------
from sklearn.model_selection import StratifiedKFold, TimeSeriesSplit
from sklearn.model_selection import train_test_split
# -----------------------------------------------------------------------------------------------------------------------------------------------------
# Pipelines
# -----------------------------------------------------------------------------------------------------------------------------------------------------
from sklearn.pipeline import Pipeline, make_pipeline
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import FunctionTransformer
from sklearn.compose import TransformedTargetRegressor
# -----------------------------------------------------------------------------------------------------------------------------------------------------
# Pre- & postprocessing
# -----------------------------------------------------------------------------------------------------------------------------------------------------
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import PowerTransformer
from sklearn.compose import TransformedTargetRegressor
from mlframe.preprocessing import prepare_df_for_catboost
# -----------------------------------------------------------------------------------------------------------------------------------------------------
# FIs
# -----------------------------------------------------------------------------------------------------------------------------------------------------
import shap
from mlframe.feature_importance import show_shap_beeswarm_plot
from mlframe.feature_importance import plot_feature_importance
# -----------------------------------------------------------------------------------------------------------------------------------------------------
# Metrics
# -----------------------------------------------------------------------------------------------------------------------------------------------------
from sklearn.metrics import make_scorer
from sklearn.metrics import roc_auc_score
from mlframe.metrics import create_robustness_subgroups
from mlframe.metrics import fast_roc_auc, fast_calibration_report, compute_probabilistic_multiclass_error, CB_EVAL_METRIC
from mlframe.metrics import create_robustness_subgroups, create_robustness_subgroups_indices, compute_robustness_metrics, robust_mlperf_metric
from sklearn.metrics import classification_report, roc_auc_score, average_precision_score
from sklearn.metrics import mean_absolute_error, max_error, mean_absolute_percentage_error, mean_squared_error
try:
from sklearn.metrics import root_mean_squared_error
except Exception as e:
def root_mean_squared_error(y_true, y_pred, *, sample_weight=None, multioutput="uniform_average"):
output_errors = np.sqrt(mean_squared_error(y_true, y_pred, sample_weight=sample_weight, multioutput="raw_values"))
if isinstance(multioutput, str):
if multioutput == "raw_values":
return output_errors
elif multioutput == "uniform_average":
# pass None as weights to np.average: uniform mean
multioutput = None
return np.average(output_errors, weights=multioutput)
# ----------------------------------------------------------------------------------------------------------------------------
# Helpers
# ----------------------------------------------------------------------------------------------------------------------------
def get_function_param_names(func):
signature = inspect.signature(func)
return list(signature.parameters.keys())
# ----------------------------------------------------------------------------------------------------------------------------
# Inits
# ----------------------------------------------------------------------------------------------------------------------------
import sklearn
sklearn.set_config(transform_output="pandas") # need this for val_df = pre_pipeline.transform(val_df) to work for SimpleImputer
CUDA_IS_AVAILABLE = is_cuda_available()
DATA_DIR = ""
if DATA_DIR:
ensure_dir_exists(DATA_DIR)
MODELS_SUBDIR = "models"
all_results = {}
# ----------------------------------------------------------------------------------------------------------------------------
# Custom Error Metrics & training configs
# ----------------------------------------------------------------------------------------------------------------------------
def get_training_configs(
iterations: int = 5000,
early_stopping_rounds: int = 0,
validation_fraction: float = 0.1,
use_explicit_early_stopping: bool = True,
has_time: bool = True,
has_gpu: bool = None,
subgroups: dict = None,
learning_rate: float = 0.1,
def_regr_metric: str = "MAE",
def_classif_metric: str = "AUC",
catboost_custom_classif_metrics: Sequence = ["AUC", "BrierScore", "PRAUC"],
catboost_custom_regr_metrics: Sequence = ["RMSE", "MAPE"],
random_seed=None,
verbose: int = 0,
# ----------------------------------------------------------------------------------------------------------------------------
# probabilistic errors
# ----------------------------------------------------------------------------------------------------------------------------
method: str = "multicrit",
mae_weight: float = 3,
std_weight: float = 3,
roc_auc_weight: float = 1.0,
brier_loss_weight: float = 0.4,
min_roc_auc: float = 0.54,
roc_auc_penalty: float = 0.00,
use_weighted_calibration: bool = True,
weight_by_class_npositives: bool = False,
nbins: int = 100,
cb_kwargs: dict = {},
lgb_kwargs: dict = {},
xgb_kwargs: dict = {},
# ----------------------------------------------------------------------------------------------------------------------------
# featureselectors
# ----------------------------------------------------------------------------------------------------------------------------
max_runtime_mins: float = 60 * 2,
max_noimproving_iters: int = 40,
cv=None,
cv_n_splits: int = 2,
) -> tuple:
"""Returns approximately same training configs for different types of models,
based on general params supplied like learning rate, task type, time budget.
Useful for more or less fair comparison between different models on the same data/task, and their upcoming ensembling.
This procedure is good for manual EDA and getting the feeling of what ML models are capable of for a particular task.
"""
if has_gpu is None:
has_gpu = CUDA_IS_AVAILABLE
if not early_stopping_rounds:
early_stopping_rounds = max(2, iterations // 3)
def neg_ovr_roc_auc_score(*args, **kwargs):
return -roc_auc_score(*args, **kwargs, multi_class="ovr")
CB_GENERAL_PARAMS = dict(
iterations=iterations,
verbose=verbose,
has_time=has_time,
learning_rate=learning_rate,
eval_fraction=(0.0 if use_explicit_early_stopping else validation_fraction),
task_type=("GPU" if has_gpu else "CPU"),
early_stopping_rounds=early_stopping_rounds,
random_seed=random_seed,
**cb_kwargs,
)
CB_CLASSIF = CB_GENERAL_PARAMS.copy()
CB_CLASSIF.update({"eval_metric": def_classif_metric, "custom_metric": catboost_custom_classif_metrics})
CB_REGR = CB_GENERAL_PARAMS.copy()
CB_REGR.update({"eval_metric": def_regr_metric, "custom_metric": catboost_custom_regr_metrics})
XGB_GENERAL_PARAMS = dict(
n_estimators=iterations,
enable_categorical=True,
max_cat_to_onehot=1,
max_cat_threshold=100, # affects model size heavily when high cardinality cat features r present!
tree_method="hist",
device=("cuda" if has_gpu else "cpu"),
n_jobs=psutil.cpu_count(logical=False),
early_stopping_rounds=early_stopping_rounds,
random_seed=random_seed,
verbosity=int(verbose),
**xgb_kwargs,
)
XGB_GENERAL_CLASSIF = XGB_GENERAL_PARAMS.copy()
XGB_GENERAL_CLASSIF.update({"objective": "binary:logistic", "eval_metric": neg_ovr_roc_auc_score})
def integral_calibration_error(y_true, y_score, verbose: bool = False):
err = compute_probabilistic_multiclass_error(
y_true=y_true,
y_score=y_score,
method=method,
mae_weight=mae_weight,
std_weight=std_weight,
brier_loss_weight=brier_loss_weight,
roc_auc_weight=roc_auc_weight,
min_roc_auc=min_roc_auc,
roc_auc_penalty=roc_auc_penalty,
use_weighted_calibration=use_weighted_calibration,
weight_by_class_npositives=weight_by_class_npositives,
nbins=nbins,
verbose=verbose,
)
if verbose:
print(len(y_true), "integral_calibration_error=", err)
return err
if subgroups:
# final_integral_calibration_error=partial(robust_mlperf_metric,metric=integral_calibration_error,higher_is_better=False,subgroups=subgroups)
def final_integral_calibration_error(y_true: np.ndarray, y_score: np.ndarray, *args, **kwargs): # partial won't work with xgboost
return robust_mlperf_metric(
y_true,
y_score,
*args,
metric=integral_calibration_error,
higher_is_better=False,
subgroups=subgroups,
**kwargs,
)
else:
final_integral_calibration_error = integral_calibration_error
def fs_and_hpt_integral_calibration_error(*args, verbose: bool = False, **kwargs):
err = compute_probabilistic_multiclass_error(
*args,
**kwargs,
mae_weight=mae_weight,
std_weight=std_weight,
brier_loss_weight=brier_loss_weight,
roc_auc_weight=roc_auc_weight,
min_roc_auc=min_roc_auc,
roc_auc_penalty=roc_auc_penalty,
use_weighted_calibration=use_weighted_calibration,
weight_by_class_npositives=weight_by_class_npositives,
nbins=nbins,
verbose=verbose,
)
return err
XGB_CALIB_CLASSIF = XGB_GENERAL_CLASSIF.copy()
XGB_CALIB_CLASSIF.update({"eval_metric": final_integral_calibration_error})
def lgbm_integral_calibration_error(y_true, y_score):
metric_name = "integral_calibration_error"
value = final_integral_calibration_error(y_true, y_score)
higher_is_better = False
return metric_name, value, higher_is_better
CB_CALIB_CLASSIF = CB_CLASSIF.copy()
CB_CALIB_CLASSIF.update({"eval_metric": CB_EVAL_METRIC(metric=final_integral_calibration_error, higher_is_better=False, max_arr_size=0)})
LGB_GENERAL_PARAMS = dict(
n_estimators=iterations,
early_stopping_rounds=early_stopping_rounds,
device_type=("cuda" if has_gpu else "cpu"),
verbose=int(verbose),
random_state=random_seed,
# histogram_pool_size=16384,
**lgb_kwargs,
)
"""device_type 🔗︎, default = cpu, type = enum, options: cpu, gpu, cuda, aliases: device
device for the tree learning
cpu supports all LightGBM functionality and is portable across the widest range of operating systems and hardware
cuda offers faster training than gpu or cpu, but only works on GPUs supporting CUDA
gpu can be faster than cpu and works on a wider range of GPUs than CUDA
Note: it is recommended to use the smaller max_bin (e.g. 63) to get the better speed up"""
# XGB_CALIB_CLASSIF_CPU.update({"device": "cpu","n_jobs":psutil.cpu_count(logical=False)})
if not cv:
if has_time:
cv = TimeSeriesSplit(n_splits=cv_n_splits)
else:
cv = StratifiedKFold(n_splits=cv_n_splits, shuffle=not has_time)
COMMON_RFECV_PARAMS = dict(
cv=cv,
cv_shuffle=not has_time,
skip_retraining_on_same_shape=True,
top_predictors_search_method=OptimumSearch.ModelBasedHeuristic,
votes_aggregation_method=VotesAggregation.Borda,
early_stopping_rounds=early_stopping_rounds,
use_last_fi_run_only=False,
verbose=True,
show_plot=True,
keep_estimators=False,
feature_cost=0.0 / 100,
smooth_perf=0,
max_refits=None,
max_runtime_mins=max_runtime_mins,
max_noimproving_iters=max_noimproving_iters,
# frac=0.2,
)
return SimpleNamespace(
integral_calibration_error=integral_calibration_error,
final_integral_calibration_error=final_integral_calibration_error,
lgbm_integral_calibration_error=lgbm_integral_calibration_error,
fs_and_hpt_integral_calibration_error=fs_and_hpt_integral_calibration_error,
CB_GENERAL_PARAMS=CB_GENERAL_PARAMS,
CB_REGR=CB_REGR,
CB_CLASSIF=CB_CLASSIF,
CB_CALIB_CLASSIF=CB_CALIB_CLASSIF,
LGB_GENERAL_PARAMS=LGB_GENERAL_PARAMS,
XGB_GENERAL_PARAMS=XGB_GENERAL_PARAMS,
XGB_GENERAL_CLASSIF=XGB_GENERAL_CLASSIF,
XGB_CALIB_CLASSIF=XGB_CALIB_CLASSIF,
COMMON_RFECV_PARAMS=COMMON_RFECV_PARAMS,
)
# -----------------------------------------------------------------------------------------------------------------------------------------------------
# Core
# -----------------------------------------------------------------------------------------------------------------------------------------------------
def train_and_evaluate_model(
model: object, # s
df: pd.DataFrame = None,
target: pd.Series = None, # s
outlier_detector: object = None,
od_val_set: bool = True,
sample_weight: pd.Series = None,
model_name: str = "",
pre_pipeline: TransformerMixin = None,
fit_params: Optional[dict] = None,
drop_columns: list = [],
default_drop_columns: list = [],
target_label_encoder: Optional[LabelEncoder] = None,
train_df: pd.DataFrame = None,
test_df: pd.DataFrame = None,
val_df: pd.DataFrame = None,
train_target: pd.Series = None,
test_target: pd.Series = None,
val_target: pd.Series = None,
train_idx: Optional[np.ndarray] = None,
test_idx: Optional[np.ndarray] = None,
val_idx: Optional[np.ndarray] = None,
train_preds: Optional[np.ndarray] = None,
train_probs: Optional[np.ndarray] = None,
test_preds: Optional[np.ndarray] = None,
test_probs: Optional[np.ndarray] = None,
val_preds: Optional[np.ndarray] = None,
val_probs: Optional[np.ndarray] = None,
custom_ice_metric: Callable = None,
custom_rice_metric: Callable = None,
subgroups: dict = None,
figsize: tuple = (15, 5),
print_report: bool = True,
show_perf_chart: bool = True,
show_fi: bool = True,
use_cache: bool = False,
nbins: int = 100,
compute_trainset_metrics: bool = False,
compute_valset_metrics: bool = True,
compute_testset_metrics: bool = True,
data_dir: str = DATA_DIR,
models_subdir: str = MODELS_SUBDIR,
display_sample_size: int = 0,
show_feature_names: bool = False,
verbose: bool = False,
use_hpt: bool = False,
# confidence_analysis
include_confidence_analysis: bool = False,
confidence_analysis_use_shap: bool = True,
confidence_analysis_max_features: int = 6,
confidence_analysis_cmap: str = "bwr",
confidence_analysis_alpha: float = 0.9,
confidence_analysis_ylabel: str = "Feature value",
confidence_analysis_title: str = "Confidence of correct Test set predictions",
confidence_model_kwargs: dict = {},
):
"""Trains & evaluates given model/pipeline on train/test sets.
Supports feature selection via pre_pipeline.
Supports early stopping via val_idx.
Optionally dumps resulting model & test set predictions into the models dir, and loads back by model name on the next call, to save time.
Example of real OD:
outlier_detector=Pipeline([("enc",ColumnTransformer(transformers=[('enc', ce.CatBoostEncoder(),['secid'])],remainder='passthrough')),("imp", SimpleImputer()), ("est", IsolationForest(contamination=0.01,n_estimators=500,n_jobs=-1))])
"""
clean_ram()
columns = []
best_iter = None
if df is not None:
check_for_infinity(df)
else:
if train_df is not None:
check_for_infinity(train_df)
if not custom_ice_metric:
custom_ice_metric = compute_probabilistic_multiclass_error
ensure_dir_exists(join(data_dir, models_subdir))
model_file_name = join(data_dir, models_subdir, f"{model_name}.dump")
if use_cache and exists(model_file_name):
logger.info(f"Loading model from file {model_file_name}")
model, *_, pre_pipeline = joblib.load(model_file_name)
if df is not None:
real_drop_columns = [col for col in drop_columns + default_drop_columns if col in df.columns]
elif train_df is not None:
real_drop_columns = [col for col in drop_columns + default_drop_columns if col in train_df.columns]
if type(model).__name__ == "Pipeline":
model_obj = model.named_steps["est"] # model.steps[-1]
else:
model_obj = model
if model_obj is not None:
if isinstance(model_obj, TransformedTargetRegressor):
model_obj = model_obj.regressor
model_type_name = type(model_obj).__name__ if model_obj is not None else ""
if model_type_name not in model_name:
model_name = model_type_name + " " + model_name
if fit_params is None:
fit_params = {}
train_od_idx, val_od_idx = None, None
if train_target is None:
train_target = target.loc[train_idx]
if val_target is None and val_idx is not None:
val_target = target.loc[val_idx]
if test_target is None and test_idx is not None:
test_target = target.loc[test_idx]
if (df is not None) or (train_df is not None):
if train_df is None:
train_df = df.loc[train_idx].drop(columns=real_drop_columns)
if val_df is None and val_idx is not None:
val_df = df.loc[val_idx].drop(columns=real_drop_columns)
# -----------------------------------------------------------------------------------------------------------------------------------------------------
# Place to inject Outlier Detector [OD] here!
# -----------------------------------------------------------------------------------------------------------------------------------------------------
if outlier_detector is not None:
outlier_detector.fit(train_df, train_target)
# train
is_inlier = outlier_detector.predict(train_df)
train_od_idx = is_inlier == 1
if train_od_idx.sum() < len(train_df):
logger.info(f"Outlier rejection: received {len(train_df):_} train samples, kept {train_od_idx.sum():_}.")
if train_idx is not None:
train_idx = train_idx[train_od_idx]
train_df = df.loc[train_idx].drop(columns=real_drop_columns)
train_target = target.loc[train_idx]
else:
train_df = train_df.loc[train_od_idx, :]
train_target = train_target.loc[train_od_idx]
# val
if val_df is not None and od_val_set:
is_inlier = outlier_detector.predict(val_df)
val_od_idx = is_inlier == 1
if val_od_idx.sum() < len(val_df):
logger.info(f"Outlier rejection: received {len(val_df):_} val samples, kept {val_od_idx.sum():_}.")
if val_idx is not None:
val_idx = val_idx[val_od_idx]
val_df = df.loc[val_idx].drop(columns=real_drop_columns)
val_target = target.loc[val_idx]
else:
val_df = val_df.loc[val_od_idx, :]
val_target = val_target.loc[val_od_idx]
clean_ram()
if model is not None and pre_pipeline:
if use_cache and exists(model_file_name):
train_df = pre_pipeline.transform(train_df, train_target)
else:
train_df = pre_pipeline.fit_transform(train_df, train_target)
if val_df is not None:
val_df = pre_pipeline.transform(val_df)
clean_ram()
if val_df is not None:
# insert eval_set where needed
if model_type_name in LGBM_MODEL_TYPES:
fit_params["eval_set"] = (val_df, val_target)
# fit_params["callbacks"] = [lgb.early_stopping(stopping_rounds=early_stopping_rounds)]
elif model_type_name in CATBOOST_MODEL_TYPES or model_type_name in XGBOOST_MODEL_TYPES:
fit_params["eval_set"] = [
(val_df, val_target),
]
elif model_type_name in TABNET_MODEL_TYPES:
fit_params["eval_set"] = [
(val_df.values, val_target.values),
]
elif model_type_name in PYTORCH_MODEL_TYPES:
fit_params["eval_set"] = (val_df, val_target)
clean_ram()
if model is not None and fit_params:
if "cat_features" in fit_params:
fit_params["cat_features"] = [
col for col in fit_params["cat_features"] if col in train_df.head(5).select_dtypes(["category", "object"]).columns.tolist()
]
if model is not None:
if (not use_cache) or (not exists(model_file_name)):
if sample_weight is not None:
if "sample_weight" in get_function_param_names(model_obj.fit):
if train_idx is not None:
fit_params["sample_weight"] = sample_weight.loc[train_idx].values
else:
fit_params["sample_weight"] = sample_weight.values
if verbose:
logger.info(f"{model_name} training dataset shape: {train_df.shape}")
if display_sample_size:
display(train_df.head(display_sample_size).style.set_caption(f"{model_name} features head"))
display(train_df.tail(display_sample_size).style.set_caption(f"{model_name} features tail"))
if train_df is not None:
report_title = f"Training {model_name} model on {train_df.shape[1]} feature(s)" # textwrap.shorten("Hello world", width=10, placeholder="...")
if show_feature_names:
report_title += ": " + ", ".join(train_df.columns.to_list())
report_title += f", {len(train_df):_} records"
if model_type_name in TABNET_MODEL_TYPES:
train_df = train_df.values
if fit_params and type(model).__name__ == "Pipeline":
fit_params = prefix_dict_elems(fit_params, "est__")
if use_hpt:
import optuna
def objective(trial):
param = {
"objective": trial.suggest_categorical("objective", ["Logloss", "CrossEntropy"]),
"colsample_bylevel": trial.suggest_float("colsample_bylevel", 0.01, 0.1),
"depth": trial.suggest_int("depth", 1, 12),
"boosting_type": trial.suggest_categorical("boosting_type", ["Ordered", "Plain"]),
"bootstrap_type": trial.suggest_categorical("bootstrap_type", ["Bayesian", "Bernoulli", "MVS"]),
}
if param["bootstrap_type"] == "Bayesian":
param["bagging_temperature"] = trial.suggest_float("bagging_temperature", 0, 10)
elif param["bootstrap_type"] == "Bernoulli":
param["subsample"] = trial.suggest_float("subsample", 0.1, 1)
tune_model = model.copy()
tune_model.set_params(**param)
clean_ram()
tune_model.fit(train_df, train_target, **fit_params)
clean_ram()
temp_metrics = {}
columns = val_df.columns
tune_val_preds, tune_val_probs = report_model_perf(
targets=val_target,
columns=columns,
df=val_df.values if model_type_name in TABNET_MODEL_TYPES else val_df,
model_name="VAL " + model_name,
model=tune_model,
target_label_encoder=target_label_encoder,
preds=val_preds,
probs=val_probs,
figsize=figsize,
report_title="",
nbins=nbins,
print_report=False,
show_perf_chart=False,
show_fi=False,
subgroups=subgroups,
subset_index=val_idx,
custom_ice_metric=custom_ice_metric,
custom_rice_metric=custom_rice_metric,
metrics=temp_metrics,
)
return temp_metrics[1]["class_robust_integral_error"]
study = optuna.create_study(direction="minimize")
study.optimize(objective, n_trials=100, timeout=60 * 60)
print("Number of finished trials: {}".format(len(study.trials)))
print("Best trial:")
trial = study.best_trial
print(" Value: {}".format(trial.value))
print(" Params: ", trial.params)
model.set_params(**trial.params)
clean_ram()
model.fit(train_df, train_target, **fit_params)
clean_ram()
if model is not None:
# get number of the best iteration
try:
best_iter = get_model_best_iter(model_obj)
if best_iter:
print(f"es_best_iter: {best_iter:_}")
except Exception as e:
logger.warning(e)
metrics = {"train": {}, "val": {}, "test": {}, "best_iter": best_iter}
if compute_trainset_metrics or compute_valset_metrics or compute_testset_metrics:
if compute_trainset_metrics and (train_idx is not None or train_df is not None):
if df is None and train_df is None:
train_df = None
columns = []
else:
columns = train_df.columns
train_preds, train_probs = report_model_perf(
targets=train_target,
columns=columns,
df=train_df.values if model_type_name in TABNET_MODEL_TYPES else train_df,
model_name="TRAIN " + model_name,
model=model,
target_label_encoder=target_label_encoder,
preds=train_preds,
probs=train_probs,
figsize=figsize,
report_title="",
nbins=nbins,
print_report=print_report,
show_perf_chart=show_perf_chart,
show_fi=False,
subgroups=subgroups,
subset_index=train_idx,
custom_ice_metric=custom_ice_metric,
custom_rice_metric=custom_rice_metric,
metrics=metrics["train"],
)
if compute_valset_metrics and ((val_idx is not None and len(val_idx) > 0) or val_df is not None):
if df is None and val_df is None:
val_df = None
columns = []
else:
columns = val_df.columns
val_preds, val_probs = report_model_perf(
targets=val_target,
columns=columns,
df=val_df.values if model_type_name in TABNET_MODEL_TYPES else val_df,
model_name="VAL " + model_name,
model=model,
target_label_encoder=target_label_encoder,
preds=val_preds,
probs=val_probs,
figsize=figsize,
report_title="",
nbins=nbins,
print_report=print_report,
show_perf_chart=show_perf_chart,
show_fi=False,
subgroups=subgroups,
subset_index=val_idx,
custom_ice_metric=custom_ice_metric,
custom_rice_metric=custom_rice_metric,
metrics=metrics["val"],
)
if compute_testset_metrics and ((test_idx is not None and len(test_idx) > 0) or test_df is not None):
if (df is not None) or (test_df is not None):
del train_df
clean_ram()
if test_df is None:
test_df = df.loc[test_idx].drop(columns=real_drop_columns)
if test_target is None:
test_target = target.loc[test_idx]
if model is not None and pre_pipeline:
test_df = pre_pipeline.transform(test_df)
if model_type_name in TABNET_MODEL_TYPES:
test_df = test_df.values
columns = test_df.columns
else:
columns = []
test_df = None
test_preds, test_probs = report_model_perf(
targets=test_target,
columns=columns,
df=test_df,
model_name="TEST " + model_name,
model=model,
target_label_encoder=target_label_encoder,
preds=test_preds,
probs=test_probs,
figsize=figsize,
report_title="",
nbins=nbins,
print_report=print_report,
show_perf_chart=show_perf_chart,
show_fi=show_fi,
subgroups=subgroups,
subset_index=test_idx,
custom_ice_metric=custom_ice_metric,
custom_rice_metric=custom_rice_metric,
metrics=metrics["test"],
)
if include_confidence_analysis:
"""Separate analysis: having original dataset, and test predictions made by a trained model,
find what original factors are the most discriminative regarding prediction accuracy. for that,
training a meta-model on test set could do it. use original features, as targets use prediction-ground truth,
train a regression boosting & check its feature importances."""
# for (any, even multiclass) classification, targets are probs of ground truth classes
if test_df is not None:
confidence_model = CatBoostRegressor(
verbose=0, eval_fraction=0.1, task_type=("GPU" if CUDA_IS_AVAILABLE else "CPU"), **confidence_model_kwargs
)
if model_type_name == type(confidence_model).__name__:
fit_params_copy = copy.copy(fit_params)
if "eval_set" in fit_params_copy:
del fit_params_copy["eval_set"]
else:
fit_params_copy = {}
if "cat_features" not in fit_params_copy:
fit_params_copy["cat_features"] = test_df.head().select_dtypes("category").columns.tolist()
fit_params_copy["plot"] = False
clean_ram()
confidence_model.fit(test_df, test_probs[np.arange(test_probs.shape[0]), test_target], **fit_params_copy)
clean_ram()
if confidence_analysis_use_shap:
explainer = shap.TreeExplainer(confidence_model)
shap_values = explainer(test_df)
shap.plots.beeswarm(
shap_values,
max_display=confidence_analysis_max_features,
color=plt.get_cmap(confidence_analysis_cmap),
alpha=confidence_analysis_alpha,
color_bar_label=confidence_analysis_ylabel,
show=False,
)
plt.xlabel(confidence_analysis_title)
plt.show()
else:
plot_model_feature_importances(
model=confidence_model,
columns=test_df.columns,
model_name=confidence_analysis_title,
num_factors=confidence_analysis_max_features,
figsize=(figsize[0] * 0.7, figsize[1] / 2),
)
clean_ram()
return SimpleNamespace(
model=model,
test_preds=test_preds,
test_probs=test_probs,
val_preds=val_preds,
val_probs=val_probs,
train_preds=train_preds,
train_probs=train_probs,
metrics=metrics,
columns=columns,
pre_pipeline=pre_pipeline,
outlier_detector=outlier_detector,
train_od_idx=train_od_idx,
val_od_idx=val_od_idx,
)
def report_model_perf(
targets: Union[np.ndarray, pd.Series],
columns: Sequence,
model_name: str,
model: ClassifierMixin,
subgroups: dict = None,
subset_index: np.ndarray = None,
report_ndigits: int = 4,
figsize: tuple = (15, 5),
report_title: str = "",
use_weights: bool = True,
calib_report_ndigits: int = 2,
verbose: bool = False,
classes: Sequence = [],
preds: Optional[np.ndarray] = None,
probs: Optional[np.ndarray] = None,
df: Optional[pd.DataFrame] = None,
target_label_encoder: Optional[LabelEncoder] = None,
nbins: int = 100,
print_report: bool = True,
show_perf_chart: bool = True,
show_fi: bool = True,
custom_ice_metric: Callable = None,
custom_rice_metric: Callable = None,
metrics: dict = None,
):
if probs is not None or is_classifier(model):
return report_probabilistic_model_perf(
targets=targets,
columns=columns,
model_name=model_name,
model=model,
subgroups=subgroups,
subset_index=subset_index,
report_ndigits=report_ndigits,
figsize=figsize,
report_title=report_title,
use_weights=use_weights,
calib_report_ndigits=calib_report_ndigits,
verbose=verbose,
classes=classes,
preds=preds,
probs=probs,
df=df,
target_label_encoder=target_label_encoder,
nbins=nbins,