-
Notifications
You must be signed in to change notification settings - Fork 4
/
tabular.py
10484 lines (8496 loc) · 349 KB
/
tabular.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
# Module: Classification
# Author: Moez Ali <moez.ali@queensu.ca>
# License: MIT
# Release: PyCaret 2.2
# Last modified : 26/08/2020
from enum import Enum, auto
import math
from pycaret.internal.meta_estimators import (
PowerTransformedTargetRegressor,
get_estimator_from_meta_estimator,
)
from pycaret.internal.pipeline import (
add_estimator_to_pipeline,
get_pipeline_estimator_label,
make_internal_pipeline,
estimator_pipeline,
merge_pipelines,
Pipeline as InternalPipeline,
)
from pycaret.internal.utils import (
color_df,
normalize_custom_transformers,
nullcontext,
true_warm_start,
can_early_stop,
infer_ml_usecase,
set_n_jobs,
)
import pycaret.internal.patches.sklearn
import pycaret.internal.patches.yellowbrick
from pycaret.internal.logging import get_logger
from pycaret.internal.plots.yellowbrick import show_yellowbrick_plot
from pycaret.internal.plots.helper import MatplotlibDefaultDPI
from pycaret.internal.Display import Display, is_in_colab
from pycaret.internal.distributions import *
from pycaret.internal.validation import *
from pycaret.internal.tunable import TunableMixin
import pycaret.containers.metrics.classification
import pycaret.containers.metrics.regression
import pycaret.containers.metrics.clustering
import pycaret.containers.metrics.anomaly
import pycaret.containers.models.classification
import pycaret.containers.models.regression
import pycaret.containers.models.clustering
import pycaret.containers.models.anomaly
import pycaret.internal.preprocess
import pandas as pd
import numpy as np
import os
import sys
import datetime
import time
import random
import gc
import multiprocessing
from copy import deepcopy
from sklearn.base import clone
from sklearn.exceptions import NotFittedError
from sklearn.compose import TransformedTargetRegressor
from sklearn.preprocessing import LabelEncoder
from typing import List, Tuple, Any, Union, Optional, Dict
from collections import Iterable
import warnings
from IPython.utils import io
import traceback
from unittest.mock import patch
import plotly.express as px
import plotly.graph_objects as go
import scikitplot as skplt
from packaging import version
warnings.filterwarnings("ignore")
_available_plots = {}
class MLUsecase(Enum):
CLASSIFICATION = auto()
REGRESSION = auto()
CLUSTERING = auto()
ANOMALY = auto()
def _is_unsupervised(ml_usecase: MLUsecase) -> bool:
return ml_usecase == MLUsecase.CLUSTERING or ml_usecase == MLUsecase.ANOMALY
def setup(
data: pd.DataFrame,
target: str,
ml_usecase: str,
available_plots: dict,
train_size: float = 0.7,
test_data: Optional[pd.DataFrame] = None,
preprocess: bool = True,
imputation_type: str = "simple",
iterative_imputation_iters: int = 5,
categorical_features: Optional[List[str]] = None,
categorical_imputation: str = "mode",
categorical_iterative_imputer: Union[str, Any] = "lightgbm",
ordinal_features: Optional[Dict[str, list]] = None,
high_cardinality_features: Optional[List[str]] = None,
high_cardinality_method: str = "frequency",
numeric_features: Optional[List[str]] = None,
numeric_imputation: str = "mean", # method 'zero' added in pycaret==2.1
numeric_iterative_imputer: Union[str, Any] = "lightgbm",
date_features: Optional[List[str]] = None,
ignore_features: Optional[List[str]] = None,
normalize: bool = False,
normalize_method: str = "zscore",
transformation: bool = False,
transformation_method: str = "yeo-johnson",
handle_unknown_categorical: bool = True,
unknown_categorical_method: str = "least_frequent",
pca: bool = False,
pca_method: str = "linear",
pca_components: Optional[float] = None,
ignore_low_variance: bool = False,
combine_rare_levels: bool = False,
rare_level_threshold: float = 0.10,
bin_numeric_features: Optional[List[str]] = None,
remove_outliers: bool = False,
outliers_threshold: float = 0.05,
remove_multicollinearity: bool = False,
multicollinearity_threshold: float = 0.9,
remove_perfect_collinearity: bool = True,
create_clusters: bool = False,
cluster_iter: int = 20,
polynomial_features: bool = False,
polynomial_degree: int = 2,
trigonometry_features: bool = False,
polynomial_threshold: float = 0.1,
group_features: Optional[List[str]] = None,
group_names: Optional[List[str]] = None,
feature_selection: bool = False,
feature_selection_threshold: float = 0.8,
feature_selection_method: str = "classic", # boruta algorithm added in pycaret==2.1
feature_interaction: bool = False,
feature_ratio: bool = False,
interaction_threshold: float = 0.01,
# classification specific
fix_imbalance: bool = False,
fix_imbalance_method: Optional[Any] = None,
# regression specific
transform_target=False,
transform_target_method="box-cox",
data_split_shuffle: bool = True,
data_split_stratify: Union[bool, List[str]] = False, # added in pycaret==2.2
fold_strategy: Union[str, Any] = "kfold", # added in pycaret==2.2
fold: int = 10, # added in pycaret==2.2
fold_shuffle: bool = False,
fold_groups: Optional[Union[str, pd.DataFrame]] = None,
n_jobs: Optional[int] = -1,
use_gpu: bool = False, # added in pycaret==2.1
custom_pipeline: Union[
Any, Tuple[str, Any], List[Any], List[Tuple[str, Any]]
] = None,
html: bool = True,
session_id: Optional[int] = None,
log_experiment: bool = False,
experiment_name: Optional[str] = None,
log_plots: Union[bool, list] = False,
log_profile: bool = False,
log_data: bool = False,
silent: bool = False,
verbose: bool = True,
profile: bool = False,
profile_kwargs: Dict[str, Any] = None,
display: Optional[Display] = None,
):
"""
This function initializes the environment in pycaret and creates the transformation
pipeline to prepare the data for modeling and deployment. setup() must called before
executing any other function in pycaret. It takes two mandatory parameters:
data and name of the target column.
All other parameters are optional.
"""
function_params_str = ", ".join(
[f"{k}={v}" for k, v in locals().items() if k != "data"]
)
global _available_plots
_available_plots = available_plots
warnings.filterwarnings("ignore")
from pycaret.utils import __version__
ver = __version__
# create logger
global logger
logger = get_logger()
logger.info("PyCaret Supervised Module")
logger.info(f"ML Usecase: {ml_usecase}")
logger.info(f"version {ver}")
logger.info("Initializing setup()")
logger.info(f"setup({function_params_str})")
# logging environment and libraries
logger.info("Checking environment")
from platform import python_version, platform, python_build, machine
logger.info(f"python_version: {python_version()}")
logger.info(f"python_build: {python_build()}")
logger.info(f"machine: {machine()}")
logger.info(f"platform: {platform()}")
try:
import psutil
logger.info(f"Memory: {psutil.virtual_memory()}")
logger.info(f"Physical Core: {psutil.cpu_count(logical=False)}")
logger.info(f"Logical Core: {psutil.cpu_count(logical=True)}")
except:
logger.warning(
"cannot find psutil installation. memory not traceable. Install psutil using pip to enable memory logging."
)
logger.info("Checking libraries")
try:
from pandas import __version__
logger.info(f"pd=={__version__}")
except ImportError:
logger.warning("pandas not found")
try:
from numpy import __version__
logger.info(f"numpy=={__version__}")
except ImportError:
logger.warning("numpy not found")
try:
from sklearn import __version__
logger.info(f"sklearn=={__version__}")
except ImportError:
logger.warning("sklearn not found")
try:
from lightgbm import __version__
logger.info(f"lightgbm=={__version__}")
except ImportError:
logger.warning("lightgbm not found")
try:
from catboost import __version__
logger.info(f"catboost=={__version__}")
except ImportError:
logger.warning("catboost not found")
try:
from xgboost import __version__
logger.info(f"xgboost=={__version__}")
except ImportError:
logger.warning("xgboost not found")
try:
from mlflow.version import VERSION
warnings.filterwarnings("ignore")
logger.info(f"mlflow=={VERSION}")
except ImportError:
logger.warning("mlflow not found")
# run_time
runtime_start = time.time()
logger.info("Checking Exceptions")
# checking data type
if not isinstance(data, pd.DataFrame):
raise TypeError(f"data passed must be of type pandas.DataFrame")
if data.shape[0] == 0:
raise ValueError(f"data passed must be a positive dataframe")
# checking train size parameter
if type(train_size) is not float:
raise TypeError("train_size parameter only accepts float value.")
if train_size <= 0 or train_size > 1:
raise ValueError("train_size parameter has to be positive and not above 1.")
possible_ml_usecases = ["classification", "regression", "clustering", "anomaly"]
if ml_usecase not in possible_ml_usecases:
raise ValueError(
f"ml_usecase must be one of {', '.join(possible_ml_usecases)}."
)
ml_usecase = MLUsecase[ml_usecase.upper()]
# checking target parameter
if not _is_unsupervised(ml_usecase) and target not in data.columns:
raise ValueError(
f"Target parameter: {target} does not exist in the data provided."
)
# checking session_id
if session_id is not None:
if type(session_id) is not int:
raise TypeError("session_id parameter must be an integer.")
# checking profile parameter
if type(profile) is not bool:
raise TypeError("profile parameter only accepts True or False.")
if profile_kwargs is not None:
if type(profile_kwargs) is not dict:
raise TypeError("profile_kwargs can only be a dict.")
else:
profile_kwargs = {}
# checking normalize parameter
if type(normalize) is not bool:
raise TypeError("normalize parameter only accepts True or False.")
# checking transformation parameter
if type(transformation) is not bool:
raise TypeError("transformation parameter only accepts True or False.")
all_cols = list(data.columns)
if not _is_unsupervised(ml_usecase):
all_cols.remove(target)
# checking imputation type
allowed_imputation_type = ["simple", "iterative"]
if imputation_type not in allowed_imputation_type:
raise ValueError(
"imputation_type parameter only accepts 'simple' or 'iterative'."
)
if type(iterative_imputation_iters) is not int or iterative_imputation_iters <= 0:
raise TypeError(
"iterative_imputation_iters parameter must be an integer greater than 0."
)
# checking categorical imputation
allowed_categorical_imputation = ["constant", "mode"]
if categorical_imputation not in allowed_categorical_imputation:
raise ValueError(
f"categorical_imputation param only accepts {', '.join(allowed_categorical_imputation)}."
)
# ordinal_features
if ordinal_features is not None:
if type(ordinal_features) is not dict:
raise TypeError(
"ordinal_features must be of type dictionary with column name as key "
"and ordered values as list."
)
# ordinal features check
if ordinal_features is not None:
ordinal_features = ordinal_features.copy()
data_cols = data.columns.drop(target, errors="ignore")
ord_keys = ordinal_features.keys()
for i in ord_keys:
if i not in data_cols:
raise ValueError(
"Column name passed as a key in ordinal_features param doesnt exist."
)
for k in ord_keys:
if data[k].nunique() != len(ordinal_features[k]):
raise ValueError(
"Levels passed in ordinal_features param doesnt match with levels in data."
)
for i in ord_keys:
value_in_keys = ordinal_features.get(i)
value_in_data = list(data[i].unique().astype(str))
for j in value_in_keys:
if str(j) not in value_in_data:
raise ValueError(
f"Column name '{i}' doesn't contain any level named '{j}'."
)
# high_cardinality_features
if high_cardinality_features is not None:
if type(high_cardinality_features) is not list:
raise TypeError(
"high_cardinality_features param only accepts name of columns as a list."
)
data_cols = data.columns.drop(target, errors="ignore")
for high_cardinality_feature in high_cardinality_features:
if high_cardinality_feature not in data_cols:
raise ValueError(
f"Item {high_cardinality_feature} in high_cardinality_features parameter is either target "
f"column or doesn't exist in the dataset."
)
# stratify
if data_split_stratify:
if (
type(data_split_stratify) is not list
and type(data_split_stratify) is not bool
):
raise TypeError(
"data_split_stratify parameter only accepts a bool or a list of strings."
)
if not data_split_shuffle:
raise TypeError(
"data_split_stratify parameter requires data_split_shuffle to be set to True."
)
# high_cardinality_methods
high_cardinality_allowed_methods = ["frequency", "clustering"]
if high_cardinality_method not in high_cardinality_allowed_methods:
raise ValueError(
f"high_cardinality_method parameter only accepts {', '.join(high_cardinality_allowed_methods)}."
)
# checking numeric imputation
allowed_numeric_imputation = ["mean", "median", "zero"]
if numeric_imputation not in allowed_numeric_imputation:
raise ValueError(
f"numeric_imputation parameter only accepts {', '.join(allowed_numeric_imputation)}."
)
# checking normalize method
allowed_normalize_method = ["zscore", "minmax", "maxabs", "robust"]
if normalize_method not in allowed_normalize_method:
raise ValueError(
f"normalize_method parameter only accepts {', '.join(allowed_normalize_method)}."
)
# checking transformation method
allowed_transformation_method = ["yeo-johnson", "quantile"]
if transformation_method not in allowed_transformation_method:
raise ValueError(
f"transformation_method parameter only accepts {', '.join(allowed_transformation_method)}."
)
# handle unknown categorical
if type(handle_unknown_categorical) is not bool:
raise TypeError(
"handle_unknown_categorical parameter only accepts True or False."
)
# unknown categorical method
unknown_categorical_method_available = ["least_frequent", "most_frequent"]
if unknown_categorical_method not in unknown_categorical_method_available:
raise TypeError(
f"unknown_categorical_method parameter only accepts {', '.join(unknown_categorical_method_available)}."
)
# check pca
if type(pca) is not bool:
raise TypeError("PCA parameter only accepts True or False.")
# pca method check
allowed_pca_methods = ["linear", "kernel", "incremental"]
if pca_method not in allowed_pca_methods:
raise ValueError(
f"pca method parameter only accepts {', '.join(allowed_pca_methods)}."
)
# pca components check
if pca is True:
if pca_method != "linear":
if pca_components is not None:
if (type(pca_components)) is not int:
raise TypeError(
"pca_components parameter must be integer when pca_method is not 'linear'."
)
# pca components check 2
if pca is True:
if pca_method != "linear":
if pca_components is not None:
if pca_components > len(data.columns) - 1:
raise TypeError(
"pca_components parameter cannot be greater than original features space."
)
# pca components check 3
if pca is True:
if pca_method == "linear":
if pca_components is not None:
if type(pca_components) is not float:
if pca_components > len(data.columns) - 1:
raise TypeError(
"pca_components parameter cannot be greater than original features space or float between 0 - 1."
)
# check ignore_low_variance
if type(ignore_low_variance) is not bool:
raise TypeError("ignore_low_variance parameter only accepts True or False.")
# check ignore_low_variance
if type(combine_rare_levels) is not bool:
raise TypeError("combine_rare_levels parameter only accepts True or False.")
# check rare_level_threshold
if (
type(rare_level_threshold) is not float
and rare_level_threshold < 0
or rare_level_threshold > 1
):
raise TypeError(
"rare_level_threshold parameter must be a float between 0 and 1."
)
# bin numeric features
if bin_numeric_features is not None:
if type(bin_numeric_features) is not list:
raise TypeError("bin_numeric_features parameter must be a list.")
for bin_numeric_feature in bin_numeric_features:
if type(bin_numeric_feature) is not str:
raise TypeError("bin_numeric_features parameter item must be a string.")
if bin_numeric_feature not in all_cols:
raise ValueError(
f"bin_numeric_feature: {bin_numeric_feature} is either target column or "
f"does not exist in the dataset."
)
# remove_outliers
if type(remove_outliers) is not bool:
raise TypeError("remove_outliers parameter only accepts True or False.")
# outliers_threshold
if type(outliers_threshold) is not float:
raise TypeError("outliers_threshold must be a float between 0 and 1.")
# remove_multicollinearity
if type(remove_multicollinearity) is not bool:
raise TypeError(
"remove_multicollinearity parameter only accepts True or False."
)
# multicollinearity_threshold
if type(multicollinearity_threshold) is not float:
raise TypeError("multicollinearity_threshold must be a float between 0 and 1.")
# create_clusters
if type(create_clusters) is not bool:
raise TypeError("create_clusters parameter only accepts True or False.")
# cluster_iter
if type(cluster_iter) is not int:
raise TypeError("cluster_iter must be a integer greater than 1.")
# polynomial_features
if type(polynomial_features) is not bool:
raise TypeError("polynomial_features only accepts True or False.")
# polynomial_degree
if type(polynomial_degree) is not int:
raise TypeError("polynomial_degree must be an integer.")
# polynomial_features
if type(trigonometry_features) is not bool:
raise TypeError("trigonometry_features only accepts True or False.")
# polynomial threshold
if type(polynomial_threshold) is not float:
raise TypeError("polynomial_threshold must be a float between 0 and 1.")
# group features
if group_features is not None:
if type(group_features) is not list:
raise TypeError("group_features must be of type list.")
if group_names is not None:
if type(group_names) is not list:
raise TypeError("group_names must be of type list.")
# cannot drop target
if ignore_features is not None:
if target in ignore_features:
raise ValueError("cannot drop target column.")
# feature_selection
if type(feature_selection) is not bool:
raise TypeError("feature_selection only accepts True or False.")
# feature_selection_threshold
if type(feature_selection_threshold) is not float:
raise TypeError("feature_selection_threshold must be a float between 0 and 1.")
# feature_selection_method
feature_selection_methods = ["boruta", "classic"]
if feature_selection_method not in feature_selection_methods:
raise TypeError(
f"feature_selection_method must be one of {', '.join(feature_selection_methods)}"
)
# feature_interaction
if type(feature_interaction) is not bool:
raise TypeError("feature_interaction only accepts True or False.")
# feature_ratio
if type(feature_ratio) is not bool:
raise TypeError("feature_ratio only accepts True or False.")
# interaction_threshold
if type(interaction_threshold) is not float:
raise TypeError("interaction_threshold must be a float between 0 and 1.")
# categorical
if categorical_features is not None:
for i in categorical_features:
if i not in all_cols:
raise ValueError(
"Column type forced is either target column or doesn't exist in the dataset."
)
# numeric
if numeric_features is not None:
for i in numeric_features:
if i not in all_cols:
raise ValueError(
"Column type forced is either target column or doesn't exist in the dataset."
)
# date features
if date_features is not None:
for i in date_features:
if i not in all_cols:
raise ValueError(
"Column type forced is either target column or doesn't exist in the dataset."
)
# drop features
if ignore_features is not None:
for i in ignore_features:
if i not in all_cols:
raise ValueError(
"Feature ignored is either target column or doesn't exist in the dataset."
)
# log_experiment
if type(log_experiment) is not bool:
raise TypeError("log_experiment parameter only accepts True or False.")
# log_profile
if type(log_profile) is not bool:
raise TypeError("log_profile parameter only accepts True or False.")
# experiment_name
if experiment_name is not None:
if type(experiment_name) is not str:
raise TypeError("experiment_name parameter must be str if not None.")
# silent
if type(silent) is not bool:
raise TypeError("silent parameter only accepts True or False.")
# remove_perfect_collinearity
if type(remove_perfect_collinearity) is not bool:
raise TypeError(
"remove_perfect_collinearity parameter only accepts True or False."
)
# html
if type(html) is not bool:
raise TypeError("html parameter only accepts True or False.")
# use_gpu
if use_gpu != "force" and type(use_gpu) is not bool:
raise TypeError("use_gpu parameter only accepts 'force', True or False.")
# data_split_shuffle
if type(data_split_shuffle) is not bool:
raise TypeError("data_split_shuffle parameter only accepts True or False.")
possible_fold_strategy = ["kfold", "stratifiedkfold", "groupkfold", "timeseries"]
if not (
fold_strategy in possible_fold_strategy
or is_sklearn_cv_generator(fold_strategy)
):
raise TypeError(
f"fold_strategy parameter must be either a scikit-learn compatible CV generator object or one of {', '.join(possible_fold_strategy)}."
)
if fold_strategy == "groupkfold" and (fold_groups is None or len(fold_groups) == 0):
raise ValueError(
"'groupkfold' fold_strategy requires 'fold_groups' to be a non-empty array-like object."
)
if isinstance(fold_groups, str):
if fold_groups not in all_cols:
raise ValueError(
f"Column {fold_groups} used for fold_groups is not present in the dataset."
)
# checking fold parameter
if type(fold) is not int:
raise TypeError("fold parameter only accepts integer value.")
# fold_shuffle
if type(fold_shuffle) is not bool:
raise TypeError("fold_shuffle parameter only accepts True or False.")
# log_plots
if isinstance(log_plots, list):
for i in log_plots:
if i not in _available_plots:
raise ValueError(
f"Incorrect value for log_plots '{i}'. Possible values are: {', '.join(_available_plots.keys())}."
)
elif type(log_plots) is not bool:
raise TypeError("log_plots parameter must be a bool or a list.")
# log_data
if type(log_data) is not bool:
raise TypeError("log_data parameter only accepts True or False.")
# fix_imbalance
if type(fix_imbalance) is not bool:
raise TypeError("fix_imbalance parameter only accepts True or False.")
# fix_imbalance_method
if fix_imbalance:
if fix_imbalance_method is not None:
if hasattr(fix_imbalance_method, "fit_resample"):
pass
else:
raise TypeError(
"fix_imbalance_method must contain resampler with fit_resample method."
)
# check transform_target
if type(transform_target) is not bool:
raise TypeError("transform_target parameter only accepts True or False.")
# transform_target_method
allowed_transform_target_method = ["box-cox", "yeo-johnson"]
if transform_target_method not in allowed_transform_target_method:
raise ValueError(
f"transform_target_method param only accepts {', '.join(allowed_transform_target_method)}."
)
# pandas option
pd.set_option("display.max_columns", 500)
pd.set_option("display.max_rows", 500)
# generate USI for mlflow tracking
import secrets
# declaring global variables to be accessed by other functions
logger.info("Declaring global variables")
global _ml_usecase, USI, html_param, X, y, X_train, X_test, y_train, y_test, seed, prep_pipe, experiment__, fold_shuffle_param, n_jobs_param, _gpu_n_jobs_param, create_model_container, master_model_container, display_container, exp_name_log, logging_param, log_plots_param, fix_imbalance_param, fix_imbalance_method_param, transform_target_param, transform_target_method_param, data_before_preprocess, target_param, gpu_param, _all_models, _all_models_internal, _all_metrics, _internal_pipeline, stratify_param, fold_generator, fold_param, fold_groups_param, fold_groups_param_full, imputation_regressor, imputation_classifier, iterative_imputation_iters_param
USI = secrets.token_hex(nbytes=2)
logger.info(f"USI: {USI}")
_ml_usecase = ml_usecase
global pycaret_globals
supervised_globals = {
"y",
"X_train",
"X_test",
"y_train",
"y_test",
}
common_globals = {
"_ml_usecase",
"_available_plots",
"pycaret_globals",
"USI",
"html_param",
"X",
"seed",
"prep_pipe",
"experiment__",
"n_jobs_param",
"_gpu_n_jobs_param",
"create_model_container",
"master_model_container",
"display_container",
"exp_name_log",
"logging_param",
"log_plots_param",
"transform_target_param",
"transform_target_method_param",
"data_before_preprocess",
"target_param",
"gpu_param",
"_all_models",
"_all_models_internal",
"_all_metrics",
"_internal_pipeline",
"imputation_regressor",
"imputation_classifier",
"iterative_imputation_iters_param",
"fold_shuffle_param",
"fix_imbalance_param",
"fix_imbalance_method_param",
"stratify_param",
"fold_generator",
"fold_param",
"fold_groups_param",
"fold_groups_param_full",
}
if not _is_unsupervised(_ml_usecase):
pycaret_globals = common_globals.union(supervised_globals)
else:
pycaret_globals = common_globals
logger.info(f"pycaret_globals: {pycaret_globals}")
# create html_param
html_param = html
logger.info("Preparing display monitor")
if not display:
# progress bar
max_steps = 3
progress_args = {"max": max_steps}
timestampStr = datetime.datetime.now().strftime("%H:%M:%S")
monitor_rows = [
["Initiated", ". . . . . . . . . . . . . . . . . .", timestampStr],
["Status", ". . . . . . . . . . . . . . . . . .", "Loading Dependencies"],
]
display = Display(
verbose=verbose,
html_param=html_param,
progress_args=progress_args,
monitor_rows=monitor_rows,
)
display.display_progress()
display.display_monitor()
logger.info("Importing libraries")
# general dependencies
from sklearn.model_selection import train_test_split
# setting sklearn config to print all parameters including default
import sklearn
sklearn.set_config(print_changed_only=False)
# define highlight function for function grid to display
def highlight_max(s):
is_max = s == True
return ["background-color: lightgreen" if v else "" for v in is_max]
logger.info("Copying data for preprocessing")
# copy original data for pandas profiler
data_before_preprocess = data.copy()
# generate seed to be used globally
seed = random.randint(150, 9000) if session_id is None else session_id
np.random.seed(seed)
_internal_pipeline = []
"""
preprocessing starts here
"""
display.update_monitor(1, "Preparing Data for Modeling")
display.display_monitor()
# define parameters for preprocessor
logger.info("Declaring preprocessing parameters")
# categorical features
cat_features_pass = categorical_features or []
# numeric features
numeric_features_pass = numeric_features or []
# drop features
ignore_features_pass = ignore_features or []
# date features
date_features_pass = date_features or []
# categorical imputation strategy
cat_dict = {"constant": "not_available", "mode": "most frequent"}
categorical_imputation_pass = cat_dict[categorical_imputation]
# transformation method strategy
trans_dict = {"yeo-johnson": "yj", "quantile": "quantile"}
trans_method_pass = trans_dict[transformation_method]
# pass method
pca_dict = {
"linear": "pca_liner",
"kernel": "pca_kernal",
"incremental": "incremental",
"pls": "pls",
}
pca_method_pass = pca_dict[pca_method]
# pca components
if pca is True:
if pca_components is None:
if pca_method == "linear":
pca_components_pass = 0.99
else:
pca_components_pass = int((len(data.columns) - 1) * 0.5)
else:
pca_components_pass = pca_components
else:
pca_components_pass = 0.99
apply_binning_pass = False if bin_numeric_features is None else True
features_to_bin_pass = bin_numeric_features or []
# trignometry
trigonometry_features_pass = ["sin", "cos", "tan"] if trigonometry_features else []
# group features
# =============#
# apply grouping
apply_grouping_pass = True if group_features is not None else False
# group features listing
if apply_grouping_pass is True:
if type(group_features[0]) is str:
group_features_pass = []
group_features_pass.append(group_features)
else:
group_features_pass = group_features
else:
group_features_pass = [[]]
# group names
if apply_grouping_pass is True:
if (group_names is None) or (len(group_names) != len(group_features_pass)):
group_names_pass = list(np.arange(len(group_features_pass)))
group_names_pass = [f"group_{i}" for i in group_names_pass]
else:
group_names_pass = group_names
else:
group_names_pass = []
# feature interactions
apply_feature_interactions_pass = (
True if feature_interaction or feature_ratio else False
)
interactions_to_apply_pass = []
if feature_interaction:
interactions_to_apply_pass.append("multiply")
if feature_ratio:
interactions_to_apply_pass.append("divide")
# unknown categorical
unkn_dict = {"least_frequent": "least frequent", "most_frequent": "most frequent"}
unknown_categorical_method_pass = unkn_dict[unknown_categorical_method]
# ordinal_features
apply_ordinal_encoding_pass = True if ordinal_features is not None else False
ordinal_columns_and_categories_pass = (
ordinal_features if apply_ordinal_encoding_pass else {}
)
apply_cardinality_reduction_pass = (
True if high_cardinality_features is not None else False
)
hi_card_dict = {"frequency": "count", "clustering": "cluster"}
cardinal_method_pass = hi_card_dict[high_cardinality_method]
cardinal_features_pass = (
high_cardinality_features if apply_cardinality_reduction_pass else []
)