forked from pycaret/pycaret
-
Notifications
You must be signed in to change notification settings - Fork 0
/
regression.py
7176 lines (5335 loc) · 261 KB
/
regression.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: Regression
# Author: Moez Ali <moez.ali@queensu.ca>
# License: MIT
def setup(data,
target,
train_size=0.7,
sampling=True,
sample_estimator = None,
categorical_features = None,
categorical_imputation = 'constant',
ordinal_features = None,
high_cardinality_features = None, #latest
high_cardinality_method = 'frequency', #latest
numeric_features = None,
numeric_imputation = 'mean',
date_features = None,
ignore_features = None,
normalize = False,
normalize_method = 'zscore',
transformation = False,
transformation_method = 'yeo-johnson',
handle_unknown_categorical = True, #new #create docstring and exception
unknown_categorical_method = 'least_frequent', #new #create docstring and exception
pca = False, #new
pca_method = 'linear', #new
pca_components = None, #new
ignore_low_variance = False, #new
combine_rare_levels = False, #new
rare_level_threshold = 0.10, #new
bin_numeric_features = None, #new
remove_outliers = False, #new
outliers_threshold = 0.05, #new
remove_multicollinearity = False, #new
multicollinearity_threshold = 0.9, #new
create_clusters = False, #new
cluster_iter = 20, #new
polynomial_features = False, #new #create checking exceptions and docstring
polynomial_degree = 2, #new #create checking exceptions and docstring
trigonometry_features = False, #new #create checking exceptions and docstring
polynomial_threshold = 0.1, #new #create checking exceptions and docstring
group_features = None, #new #create checking exceptions and docstring
group_names = None, #new #create checking exceptions and docstring
feature_selection = False, #new #create checking exceptions and docstring
feature_selection_threshold = 0.8, #new #create checking exceptions and docstring
feature_interaction = False, #new #create checking exceptions and docstring
feature_ratio = False, #new #create checking exceptions and docstring
interaction_threshold = 0.01, #new #create checking exceptions and docstring
transform_target = False, #new
transform_target_method = 'box-cox', #new
session_id = None,
silent = False,
profile = False):
"""
Description:
------------
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:
dataframe {array-like, sparse matrix} and name of the target column.
All other parameters are optional.
Example
-------
from pycaret.datasets import get_data
boston = get_data('boston')
experiment_name = setup(data = boston, target = 'medv')
'boston' is a pandas DataFrame and 'medv' is the name of target column.
Parameters
----------
data : {array-like, sparse matrix}, shape (n_samples, n_features) where n_samples
is the number of samples and n_features is the number of features.
target: string
Name of target column to be passed in as string.
train_size: float, default = 0.7
Size of the training set. By default, 70% of the data will be used for training
and validation. The remaining data will be used for test / hold-out set.
sampling: bool, default = True
When the sample size exceeds 25,000 samples, pycaret will build a base estimator
at various sample sizes from the original dataset. This will return a performance
plot of R2 values at various sample levels, that will assist in deciding the
preferred sample size for modeling. The desired sample size must then be entered
for training and validation in the pycaret environment. When sample_size entered
is less than 1, the remaining dataset (1 - sample) is used for fitting the model
only when finalize_model() is called.
sample_estimator: object, default = None
If None, Linear Regression is used by default.
categorical_features: string, default = None
If the inferred data types are not correct, categorical_features can be used to
overwrite the inferred type. If when running setup the type of 'column1' is
inferred as numeric instead of categorical, then this parameter can be used
to overwrite the type by passing categorical_features = ['column1'].
categorical_imputation: string, default = 'constant'
If missing values are found in categorical features, they will be imputed with
a constant 'not_available' value. The other available option is 'mode' which
imputes the missing value using most frequent value in the training dataset.
ordinal_features: dictionary, default = None
When the data contains ordinal features, they must be encoded differently using
the ordinal_features param. If the data has a categorical variable with values
of 'low', 'medium', 'high' and it is known that low < medium < high, then it can
be passed as ordinal_features = { 'column_name' : ['low', 'medium', 'high'] }.
The list sequence must be in increasing order from lowest to highest.
high_cardinality_features: string, default = None
When the data containts features with high cardinality, they can be compressed
into fewer levels by passing them as a list of column names with high cardinality.
Features are compressed using method defined in high_cardinality_method param.
high_cardinality_method: string, default = 'frequency'
When method set to 'frequency' it will replace the original value of feature
with the frequency distribution and convert the feature into numeric. Other
available method is 'clustering' which performs the clustering on statistical
attribute of data and replaces the original value of feature with cluster label.
The number of clusters is determined using a combination of Calinski-Harabasz and
Silhouette criterion.
numeric_features: string, default = None
If the inferred data types are not correct, numeric_features can be used to
overwrite the inferred type. If when running setup the type of 'column1' is
inferred as a categorical instead of numeric, then this parameter can be used
to overwrite by passing numeric_features = ['column1'].
numeric_imputation: string, default = 'mean'
If missing values are found in numeric features, they will be imputed with the
mean value of the feature. The other available option is 'median' which imputes
the value using the median value in the training dataset.
date_features: string, default = None
If the data has a DateTime column that is not automatically detected when running
setup, this parameter can be used by passing date_features = 'date_column_name'.
It can work with multiple date columns. Date columns are not used in modeling.
Instead, feature extraction is performed and date columns are dropped from the
dataset. If the date column includes a time stamp, features related to time will
also be extracted.
ignore_features: string, default = None
If any feature should be ignored for modeling, it can be passed to the param
ignore_features. The ID and DateTime columns when inferred, are automatically
set to ignore for modeling.
normalize: bool, default = False
When set to True, the feature space is transformed using the normalized_method
param. Generally, linear algorithms perform better with normalized data however,
the results may vary and it is advised to run multiple experiments to evaluate
the benefit of normalization.
normalize_method: string, default = 'zscore'
Defines the method to be used for normalization. By default, normalize method
is set to 'zscore'. The standard zscore is calculated as z = (x - u) / s. The
other available options are:
'minmax' : scales and translates each feature individually such that it is in
the range of 0 - 1.
'maxabs' : scales and translates each feature individually such that the maximal
absolute value of each feature will be 1.0. It does not shift/center
the data, and thus does not destroy any sparsity.
'robust' : scales and translates each feature according to the Interquartile range.
When the dataset contains outliers, robust scaler often gives better
results.
transformation: bool, default = False
When set to True, a power transformation is applied to make the data more normal /
Gaussian-like. This is useful for modeling issues related to heteroscedasticity or
other situations where normality is desired. The optimal parameter for stabilizing
variance and minimizing skewness is estimated through maximum likelihood.
transformation_method: string, default = 'yeo-johnson'
Defines the method for transformation. By default, the transformation method is set
to 'yeo-johnson'. The other available option is 'quantile' transformation. Both
the transformation transforms the feature set to follow a Gaussian-like or normal
distribution. Note that the quantile transformer is non-linear and may distort linear
correlations between variables measured at the same scale.
handle_unknown_categorical: bool, default = True
When set to True, unknown categorical levels in new / unseen data are replaced by
the most or least frequent level as learned in the training data. The method is
defined under the unknown_categorical_method param.
unknown_categorical_method: string, default = 'least_frequent'
Method used to replace unknown categorical levels in unseen data. Method can be
set to 'least_frequent' or 'most_frequent'.
pca: bool, default = False
When set to True, dimensionality reduction is applied to project the data into
a lower dimensional space using the method defined in pca_method param. In
supervised learning pca is generally performed when dealing with high feature
space and memory is a constraint. Note that not all datasets can be decomposed
efficiently using a linear PCA technique and that applying PCA may result in loss
of information. As such, it is advised to run multiple experiments with different
pca_methods to evaluate the impact.
pca_method: string, default = 'linear'
The 'linear' method performs Linear dimensionality reduction using Singular Value
Decomposition. The other available options are:
kernel : dimensionality reduction through the use of RVF kernel.
incremental : replacement for 'linear' pca when the dataset to be decomposed is
too large to fit in memory
pca_components: int/float, default = 0.99
Number of components to keep. if pca_components is a float, it is treated as a
target percentage for information retention. When pca_components is an integer
it is treated as the number of features to be kept. pca_components must be strictly
less than the original number of features in the dataset.
ignore_low_variance: bool, default = False
When set to True, all categorical features with statistically insignificant variances
are removed from the dataset. The variance is calculated using the ratio of unique
values to the number of samples, and the ratio of the most common value to the
frequency of the second most common value.
combine_rare_levels: bool, default = False
When set to True, all levels in categorical features below the threshold defined
in rare_level_threshold param are combined together as a single level. There must be
atleast two levels under the threshold for this to take effect. rare_level_threshold
represents the percentile distribution of level frequency. Generally, this technique
is applied to limit a sparse matrix caused by high numbers of levels in categorical
features.
rare_level_threshold: float, default = 0.1
Percentile distribution below which rare categories are combined. Only comes into
effect when combine_rare_levels is set to True.
bin_numeric_features: list, default = None
When a list of numeric features is passed they are transformed into categorical
features using KMeans, where values in each bin have the same nearest center of a
1D k-means cluster. The number of clusters are determined based on the 'sturges'
method. It is only optimal for gaussian data and underestimates the number of bins
for large non-gaussian datasets.
remove_outliers: bool, default = False
When set to True, outliers from the training data are removed using PCA linear
dimensionality reduction using the Singular Value Decomposition technique.
outliers_threshold: float, default = 0.05
The percentage / proportion of outliers in the dataset can be defined using
the outliers_threshold param. By default, 0.05 is used which means 0.025 of the
values on each side of the distribution's tail are dropped from training data.
remove_multicollinearity: bool, default = False
When set to True, the variables with inter-correlations higher than the threshold
defined under the multicollinearity_threshold param are dropped. When two features
are highly correlated with each other, the feature that is less correlated with
the target variable is dropped.
multicollinearity_threshold: float, default = 0.9
Threshold used for dropping the correlated features. Only comes into effect when
remove_multicollinearity is set to True.
create_clusters: bool, default = False
When set to True, an additional feature is created where each instance is assigned
to a cluster. The number of clusters is determined using a combination of
Calinski-Harabasz and Silhouette criterion.
cluster_iter: int, default = 20
Number of iterations used to create a cluster. Each iteration represents cluster
size. Only comes into effect when create_clusters param is set to True.
polynomial_features: bool, default = False
When set to True, new features are created based on all polynomial combinations
that exist within the numeric features in a dataset to the degree defined in
polynomial_degree param.
polynomial_degree: int, default = 2
Degree of polynomial features. For example, if an input sample is two dimensional
and of the form [a, b], the polynomial features with degree = 2 are:
[1, a, b, a^2, ab, b^2].
trigonometry_features: bool, default = False
When set to True, new features are created based on all trigonometric combinations
that exist within the numeric features in a dataset to the degree defined in the
polynomial_degree param.
polynomial_threshold: float, default = 0.1
This is used to compress a sparse matrix of polynomial and trigonometric features.
Polynomial and trigonometric features whose feature importance based on the
combination of Random Forest, AdaBoost and Linear correlation falls within the
percentile of the defined threshold are kept in the dataset. Remaining features
are dropped before further processing.
group_features: list or list of list, default = None
When a dataset contains features that have related characteristics, the group_features
param can be used for statistical feature extraction. For example, if a dataset has
numeric features that are related with each other (i.e 'Col1', 'Col2', 'Col3'), a list
containing the column names can be passed under group_features to extract statistical
information such as the mean, median, mode and standard deviation.
group_names: list, default = None
When group_features is passed, a name of the group can be passed into the group_names
param as a list containing strings. The length of a group_names list must equal to the
length of group_features. When the length doesn't match or the name is not passed, new
features are sequentially named such as group_1, group_2 etc.
feature_selection: bool, default = False
When set to True, a subset of features are selected using a combination of various
permutation importance techniques including Random Forest, Adaboost and Linear
correlation with target variable. The size of the subset is dependent on the
feature_selection_param. Generally, this is used to constrain the feature space
in order to improve efficiency in modeling. When polynomial_features and
feature_interaction are used, it is highly recommended to define the
feature_selection_threshold param with a lower value.
feature_selection_threshold: float, default = 0.8
Threshold used for feature selection (including newly created polynomial features).
A higher value will result in a higher feature space. It is recommended to do multiple
trials with different values of feature_selection_threshold specially in cases where
polynomial_features and feature_interaction are used. Setting a very low value may be
efficient but could result in under-fitting.
feature_interaction: bool, default = False
When set to True, it will create new features by interacting (a * b) for all numeric
variables in the dataset including polynomial and trigonometric features (if created).
This feature is not scalable and may not work as expected on datasets with large
feature space.
feature_ratio: bool, default = False
When set to True, it will create new features by calculating the ratios (a / b) of all
numeric variables in the dataset. This feature is not scalable and may not work as
expected on datasets with large feature space.
interaction_threshold: bool, default = 0.01
Similar to polynomial_threshold, It is used to compress a sparse matrix of newly
created features through interaction. Features whose importance based on the
combination of Random Forest, AdaBoost and Linear correlation falls within the
percentile of the defined threshold are kept in the dataset. Remaining features
are dropped before further processing.
transform_target: bool, default = False
When set to True, target variable is transformed using the method defined in
transform_target_method param. Target transformation is applied separately from
feature transformations.
transform_target_method: string, default = 'box-cox'
'Box-cox' and 'yeo-johnson' methods are supported. Box-Cox requires input data to
be strictly positive, while Yeo-Johnson supports both positive or negative data.
When transform_target_method is 'box-cox' and target variable contains negative
values, method is internally forced to 'yeo-johnson' to avoid exceptions.
session_id: int, default = None
If None, a random seed is generated and returned in the Information grid. The
unique number is then distributed as a seed in all functions used during the
experiment. This can be used for later reproducibility of the entire experiment.
silent: bool, default = False
When set to True, confirmation of data types is not required. All preprocessing will
be performed assuming automatically inferred data types. Not recommended for direct use
except for established pipelines.
profile: bool, default = False
If set to true, a data profile for Exploratory Data Analysis will be displayed
in an interactive HTML report.
Returns:
--------
info grid: Information grid is printed.
-----------
environment: This function returns various outputs that are stored in variable
----------- as tuple. They are used by other functions in pycaret.
Warnings:
---------
None
"""
#exception checking
import sys
#checking train size parameter
if type(train_size) is not float:
sys.exit('(Type Error): train_size parameter only accepts float value.')
#checking sampling parameter
if type(sampling) is not bool:
sys.exit('(Type Error): sampling parameter only accepts True or False.')
#checking sampling parameter
if target not in data.columns:
sys.exit('(Value Error): Target parameter doesnt exist in the data provided.')
#checking session_id
if session_id is not None:
if type(session_id) is not int:
sys.exit('(Type Error): session_id parameter must be an integer.')
#checking sampling parameter
if type(profile) is not bool:
sys.exit('(Type Error): profile parameter only accepts True or False.')
#checking normalize parameter
if type(normalize) is not bool:
sys.exit('(Type Error): normalize parameter only accepts True or False.')
#checking transformation parameter
if type(transformation) is not bool:
sys.exit('(Type Error): transformation parameter only accepts True or False.')
#checking categorical imputation
allowed_categorical_imputation = ['constant', 'mode']
if categorical_imputation not in allowed_categorical_imputation:
sys.exit("(Value Error): categorical_imputation param only accepts 'constant' or 'mode' ")
#ordinal_features
if ordinal_features is not None:
if type(ordinal_features) is not dict:
sys.exit("(Type Error): 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:
data_cols = data.columns
data_cols = data_cols.drop(target)
ord_keys = ordinal_features.keys()
for i in ord_keys:
if i not in data_cols:
sys.exit("(Value Error) Column name passed as a key in ordinal_features param doesnt exist. ")
for k in ord_keys:
if data[k].nunique() != len(ordinal_features.get(k)):
sys.exit("(Value Error) 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 j not in value_in_data:
text = "Column name '" + str(i) + "' doesnt contain any level named '" + str(j) + "'."
sys.exit(text)
#high_cardinality_features
if high_cardinality_features is not None:
if type(high_cardinality_features) is not list:
sys.exit("(Type Error): high_cardinality_features param only accepts name of columns as a list. ")
if high_cardinality_features is not None:
data_cols = data.columns
data_cols = data_cols.drop(target)
for i in high_cardinality_features:
if i not in data_cols:
sys.exit("(Value Error): Column type forced is either target column or doesn't exist in the dataset.")
#checking numeric imputation
allowed_numeric_imputation = ['mean', 'median']
if numeric_imputation not in allowed_numeric_imputation:
sys.exit("(Value Error): numeric_imputation param only accepts 'mean' or 'median' ")
#checking normalize method
allowed_normalize_method = ['zscore', 'minmax', 'maxabs', 'robust']
if normalize_method not in allowed_normalize_method:
sys.exit("(Value Error): normalize_method param only accepts 'zscore', 'minxmax', 'maxabs' or 'robust'. ")
#checking transformation method
allowed_transformation_method = ['yeo-johnson', 'quantile']
if transformation_method not in allowed_transformation_method:
sys.exit("(Value Error): transformation_method param only accepts 'yeo-johnson' or 'quantile' ")
#handle unknown categorical
if type(handle_unknown_categorical) is not bool:
sys.exit('(Type Error): 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:
sys.exit("(Type Error): unknown_categorical_method only accepts 'least_frequent' or 'most_frequent'.")
#check pca
if type(pca) is not bool:
sys.exit('(Type Error): PCA parameter only accepts True or False.')
#pca method check
allowed_pca_methods = ['linear', 'kernel', 'incremental',]
if pca_method not in allowed_pca_methods:
sys.exit("(Value Error): pca method param only accepts 'linear', 'kernel', or 'incremental'. ")
#pca components check
if pca is True:
if pca_method is not 'linear':
if pca_components is not None:
if(type(pca_components)) is not int:
sys.exit("(Type Error): pca_components parameter must be integer when pca_method is not 'linear'. ")
#pca components check 2
if pca is True:
if pca_method is not 'linear':
if pca_components is not None:
if pca_components > len(data.columns)-1:
sys.exit("(Type Error): pca_components parameter cannot be greater than original features space.")
#pca components check 3
if pca is True:
if pca_method is 'linear':
if pca_components is not None:
if type(pca_components) is not float:
if pca_components > len(data.columns)-1:
sys.exit("(Type Error): 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:
sys.exit('(Type Error): ignore_low_variance parameter only accepts True or False.')
#check ignore_low_variance
if type(combine_rare_levels) is not bool:
sys.exit('(Type Error): combine_rare_levels parameter only accepts True or False.')
#check rare_level_threshold
if type(rare_level_threshold) is not float:
sys.exit('(Type Error): rare_level_threshold must be a float between 0 and 1. ')
#bin numeric features
if bin_numeric_features is not None:
all_cols = list(data.columns)
all_cols.remove(target)
for i in bin_numeric_features:
if i not in all_cols:
sys.exit("(Value Error): Column type forced is either target column or doesn't exist in the dataset.")
#check transform_target
if type(transform_target) is not bool:
sys.exit('(Type Error): 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:
sys.exit("(Value Error): transform_target_method param only accepts 'box-cox' or 'yeo-johnson'. ")
#remove_outliers
if type(remove_outliers) is not bool:
sys.exit('(Type Error): remove_outliers parameter only accepts True or False.')
#outliers_threshold
if type(outliers_threshold) is not float:
sys.exit('(Type Error): outliers_threshold must be a float between 0 and 1. ')
#remove_multicollinearity
if type(remove_multicollinearity) is not bool:
sys.exit('(Type Error): remove_multicollinearity parameter only accepts True or False.')
#multicollinearity_threshold
if type(multicollinearity_threshold) is not float:
sys.exit('(Type Error): multicollinearity_threshold must be a float between 0 and 1. ')
#create_clusters
if type(create_clusters) is not bool:
sys.exit('(Type Error): create_clusters parameter only accepts True or False.')
#cluster_iter
if type(cluster_iter) is not int:
sys.exit('(Type Error): cluster_iter must be a integer greater than 1. ')
#polynomial_features
if type(polynomial_features) is not bool:
sys.exit('(Type Error): polynomial_features only accepts True or False. ')
#polynomial_degree
if type(polynomial_degree) is not int:
sys.exit('(Type Error): polynomial_degree must be an integer. ')
#polynomial_features
if type(trigonometry_features) is not bool:
sys.exit('(Type Error): trigonometry_features only accepts True or False. ')
#polynomial threshold
if type(polynomial_threshold) is not float:
sys.exit('(Type Error): 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:
sys.exit('(Type Error): group_features must be of type list. ')
if group_names is not None:
if type(group_names) is not list:
sys.exit('(Type Error): group_names must be of type list. ')
#cannot drop target
if ignore_features is not None:
if target in ignore_features:
sys.exit("(Value Error): cannot drop target column. ")
#feature_selection
if type(feature_selection) is not bool:
sys.exit('(Type Error): feature_selection only accepts True or False. ')
#feature_selection_threshold
if type(feature_selection_threshold) is not float:
sys.exit('(Type Error): feature_selection_threshold must be a float between 0 and 1. ')
#feature_interaction
if type(feature_interaction) is not bool:
sys.exit('(Type Error): feature_interaction only accepts True or False. ')
#feature_ratio
if type(feature_ratio) is not bool:
sys.exit('(Type Error): feature_ratio only accepts True or False. ')
#interaction_threshold
if type(interaction_threshold) is not float:
sys.exit('(Type Error): interaction_threshold must be a float between 0 and 1. ')
#cannot drop target
if ignore_features is not None:
if target in ignore_features:
sys.exit("(Value Error): cannot drop target column. ")
#forced type check
all_cols = list(data.columns)
all_cols.remove(target)
#categorical
if categorical_features is not None:
for i in categorical_features:
if i not in all_cols:
sys.exit("(Value Error): 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:
sys.exit("(Value Error): 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:
sys.exit("(Value Error): 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:
sys.exit("(Value Error): Feature ignored is either target column or doesn't exist in the dataset.")
#silent
if type(silent) is not bool:
sys.exit("(Type Error): silent parameter only accepts True or False. ")
#pre-load libraries
import pandas as pd
import ipywidgets as ipw
from IPython.display import display, HTML, clear_output, update_display
import datetime, time
#pandas option
pd.set_option('display.max_columns', 500)
pd.set_option('display.max_rows', 500)
#progress bar
if sampling:
max = 10 + 3
else:
max = 3
progress = ipw.IntProgress(value=0, min=0, max=max, step=1 , description='Processing: ')
display(progress)
timestampStr = datetime.datetime.now().strftime("%H:%M:%S")
monitor = pd.DataFrame( [ ['Initiated' , '. . . . . . . . . . . . . . . . . .', timestampStr ],
['Status' , '. . . . . . . . . . . . . . . . . .' , 'Loading Dependencies' ],
['ETC' , '. . . . . . . . . . . . . . . . . .', 'Calculating ETC'] ],
columns=['', ' ', ' ']).set_index('')
display(monitor, display_id = 'monitor')
#general dependencies
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn import metrics
import random
import seaborn as sns
import matplotlib.pyplot as plt
import plotly.express as px
#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]
#cufflinks
import cufflinks as cf
cf.go_offline()
cf.set_config_file(offline=False, world_readable=True)
#ignore warnings
import warnings
warnings.filterwarnings('ignore')
#copy original data for pandas profiler
data_before_preprocess = data.copy()
#declaring global variables to be accessed by other functions
global X, y, X_train, X_test, y_train, y_test, seed, prep_pipe, target_inverse_transformer, experiment__, preprocess
#generate seed to be used globally
if session_id is None:
seed = random.randint(150,9000)
else:
seed = session_id
"""
preprocessing starts here
"""
monitor.iloc[1,1:] = 'Preparing Data for Modeling'
update_display(monitor, display_id = 'monitor')
#define parameters for preprocessor
#categorical features
if categorical_features is None:
cat_features_pass = []
else:
cat_features_pass = categorical_features
#numeric features
if numeric_features is None:
numeric_features_pass = []
else:
numeric_features_pass = numeric_features
#drop features
if ignore_features is None:
ignore_features_pass = []
else:
ignore_features_pass = ignore_features
#date features
if date_features is None:
date_features_pass = []
else:
date_features_pass = date_features
#categorical imputation strategy
if categorical_imputation == 'constant':
categorical_imputation_pass = 'not_available'
elif categorical_imputation == 'mode':
categorical_imputation_pass = 'most frequent'
#transformation method strategy
if transformation_method == 'yeo-johnson':
trans_method_pass = 'yj'
elif transformation_method == 'quantile':
trans_method_pass = 'quantile'
#pass method
if pca_method == 'linear':
pca_method_pass = 'pca_liner'
elif pca_method == 'kernel':
pca_method_pass = 'pca_kernal'
elif pca_method == 'incremental':
pca_method_pass = 'incremental'
elif pca_method == 'pls':
pca_method_pass = 'pls'
#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
if bin_numeric_features is None:
apply_binning_pass = False
features_to_bin_pass = []
else:
apply_binning_pass = True
features_to_bin_pass = bin_numeric_features
#trignometry
if trigonometry_features is False:
trigonometry_features_pass = []
else:
trigonometry_features_pass = ['sin', 'cos', 'tan']
#group features
#=============#
#apply grouping
if group_features is not None:
apply_grouping_pass = True
else:
apply_grouping_pass = 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 = ['group_' + str(i) for i in group_names_pass]
else:
group_names_pass = group_names
else:
group_names_pass = []
#feature interactions
if feature_interaction or feature_ratio:
apply_feature_interactions_pass = True
else:
apply_feature_interactions_pass = 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
if unknown_categorical_method == 'least_frequent':
unknown_categorical_method_pass = 'least frequent'
elif unknown_categorical_method == 'most_frequent':
unknown_categorical_method_pass = 'most frequent'
#ordinal_features
if ordinal_features is not None:
apply_ordinal_encoding_pass = True
else:
apply_ordinal_encoding_pass = False
if apply_ordinal_encoding_pass is True:
ordinal_columns_and_categories_pass = ordinal_features
else:
ordinal_columns_and_categories_pass = {}
if high_cardinality_features is not None:
apply_cardinality_reduction_pass = True
else:
apply_cardinality_reduction_pass = False
if high_cardinality_method == 'frequency':
cardinal_method_pass = 'count'
elif high_cardinality_method == 'clustering':
cardinal_method_pass = 'cluster'
if apply_cardinality_reduction_pass:
cardinal_features_pass = high_cardinality_features
else:
cardinal_features_pass = []
if silent:
display_dtypes_pass = False
else:
display_dtypes_pass = True
#transform target method
if transform_target_method == 'box-cox':
transform_target_method_pass = 'bc'
elif transform_target_method == 'yeo-johnson':
transform_target_method_pass = 'yj'
#import library
from pycaret import preprocess
data = preprocess.Preprocess_Path_One(train_data = data,
target_variable = target,
categorical_features = cat_features_pass,
apply_ordinal_encoding = apply_ordinal_encoding_pass, #new
ordinal_columns_and_categories = ordinal_columns_and_categories_pass, #new
apply_cardinality_reduction = apply_cardinality_reduction_pass, #latest
cardinal_method = cardinal_method_pass, #latest
cardinal_features = cardinal_features_pass, #latest
numerical_features = numeric_features_pass,
time_features = date_features_pass,
features_todrop = ignore_features_pass,
numeric_imputation_strategy = numeric_imputation,
categorical_imputation_strategy = categorical_imputation_pass,
scale_data = normalize,
scaling_method = normalize_method,
Power_transform_data = transformation,
Power_transform_method = trans_method_pass,
apply_untrained_levels_treatment= handle_unknown_categorical, #new
untrained_levels_treatment_method = unknown_categorical_method_pass, #new
apply_pca = pca, #new
pca_method = pca_method_pass, #new
pca_variance_retained_or_number_of_components = pca_components_pass, #new
apply_zero_nearZero_variance = ignore_low_variance, #new
club_rare_levels = combine_rare_levels, #new
rara_level_threshold_percentage = rare_level_threshold, #new
apply_binning = apply_binning_pass, #new
features_to_binn = features_to_bin_pass, #new
remove_outliers = remove_outliers, #new
outlier_contamination_percentage = outliers_threshold, #new
outlier_methods = ['pca'], #pca hardcoded
remove_multicollinearity = remove_multicollinearity, #new
maximum_correlation_between_features = multicollinearity_threshold, #new
remove_perfect_collinearity = True, #latest 2
cluster_entire_data = create_clusters, #new
range_of_clusters_to_try = cluster_iter, #new
apply_polynomial_trigonometry_features = polynomial_features, #new
max_polynomial = polynomial_degree, #new
trigonometry_calculations = trigonometry_features_pass, #new
top_poly_trig_features_to_select_percentage = polynomial_threshold, #new
apply_grouping = apply_grouping_pass, #new
features_to_group_ListofList = group_features_pass, #new
group_name = group_names_pass, #new
apply_feature_selection = feature_selection, #new
feature_selection_top_features_percentage = feature_selection_threshold, #new
apply_feature_interactions = apply_feature_interactions_pass, #new
feature_interactions_to_apply = interactions_to_apply_pass, #new
feature_interactions_top_features_to_select_percentage=interaction_threshold, #new
display_types = display_dtypes_pass, #new #to be parameterized in setup later.
target_transformation = transform_target, #new
target_transformation_method = transform_target_method_pass, #new
random_state = seed)
progress.value += 1
if hasattr(preprocess.dtypes, 'replacement'):
label_encoded = preprocess.dtypes.replacement
label_encoded = str(label_encoded).replace("'", '')
label_encoded = str(label_encoded).replace("{", '')
label_encoded = str(label_encoded).replace("}", '')
else:
label_encoded = 'None'
try:
res_type = ['quit','Quit','exit','EXIT','q','Q','e','E','QUIT','Exit']
res = preprocess.dtypes.response
if res in res_type:
sys.exit("(Process Exit): setup has been interupted with user command 'quit'. setup must rerun." )
except:
pass
#save prep pipe
prep_pipe = preprocess.pipe
#save target inverse transformer
try:
target_inverse_transformer = preprocess.pt_target.p_transform_target
except:
target_inverse_transformer = None
#generate values for grid show
missing_values = data_before_preprocess.isna().sum().sum()
if missing_values > 0:
missing_flag = True
else:
missing_flag = False
if normalize is True:
normalize_grid = normalize_method
else:
normalize_grid = 'None'
if transformation is True:
transformation_grid = transformation_method