forked from pycaret/pycaret
-
Notifications
You must be signed in to change notification settings - Fork 0
/
anomaly.py
3125 lines (2333 loc) · 110 KB
/
anomaly.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: Anomaly Detection
# Author: Moez Ali <moez.ali@queensu.ca>
# License: MIT
def setup(data,
categorical_features = None,
categorical_imputation = 'constant',
ordinal_features = None, #new
high_cardinality_features = None, #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
unknown_categorical_method = 'least_frequent', #new
pca = False,
pca_method = 'linear',
pca_components = None,
ignore_low_variance = False,
combine_rare_levels = False,
rare_level_threshold = 0.10,
bin_numeric_features = None,
remove_multicollinearity = False, #new
multicollinearity_threshold = 0.9, #new
group_features = None, #new
group_names = None, #new
supervised = False,
supervised_target = None,
session_id = None,
profile = False,
verbose=True):
"""
Description:
------------
This function initializes the environment in pycaret. setup() must called before
executing any other function in pycaret. It takes one mandatory parameter:
dataframe {array-like, sparse matrix}.
Example
-------
from pycaret.datasets import get_data
anomaly = get_data('anomaly')
experiment_name = setup(data = anomaly, normalize = True)
'anomaly' is a pandas Dataframe.
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 in dataframe.
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 frequency distribution. As such original features
are replaced with the frequency distribution and converted into numeric variable.
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_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 with higher average correlation
in the feature space 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.
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.
supervised: bool, default = False
When set to True, supervised_target column is ignored for transformation. This
param is only for internal use.
supervised_target: string, default = None
Name of supervised_target column that will be ignored for transformation. Only
applciable when tune_model() function is used. This param is only for internal use.
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.
profile: bool, default = False
If set to true, a data profile for Exploratory Data Analysis will be displayed
in an interactive HTML report.
verbose: Boolean, default = True
Information grid is not printed when verbose is set to False.
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
"""
error handling starts here
"""
#checking data type
if hasattr(data,'shape') is False:
sys.exit('(Type Error): data passed must be of type pandas.DataFrame')
#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 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']
#forced type check
all_cols = list(data.columns)
#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.")
#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):
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):
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)
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.")
#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. ')
#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. ')
"""
error handling ends here
"""
#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
max_steps = 4
progress = ipw.IntProgress(value=0, min=0, max=max_steps, step=1 , description='Processing: ')
timestampStr = datetime.datetime.now().strftime("%H:%M:%S")
monitor = pd.DataFrame( [ ['Initiated' , '. . . . . . . . . . . . . . . . . .', timestampStr ],
['Status' , '. . . . . . . . . . . . . . . . . .' , 'Loading Dependencies' ] ],
#['Step' , '. . . . . . . . . . . . . . . . . .', 'Step 0 of ' + str(total_steps)] ],
columns=['', ' ', ' ']).set_index('')
if verbose:
display(progress)
display(monitor, display_id = 'monitor')
#general dependencies
import numpy as np
import pandas as pd
import random
#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]
#ignore warnings
import warnings
warnings.filterwarnings('ignore')
#defining global variables
global data_, X, seed, prep_pipe, prep_param, experiment__
#copy original data for pandas profiler
data_before_preprocess = data.copy()
#copying data
data_ = data.copy()
#data without target
if supervised:
data_without_target = data.copy()
data_without_target.drop(supervised_target, axis=1, inplace=True)
if supervised:
data_for_preprocess = data_without_target.copy()
else:
data_for_preprocess = data_.copy()
#generate seed to be used globally
if session_id is None:
seed = random.randint(150,9000)
else:
seed = session_id
"""
preprocessing starts here
"""
pd.set_option('display.max_columns', 500)
pd.set_option('display.max_rows', 500)
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))*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
#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 = []
#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 = {}
#high cardinality
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
cardinal_method_pass = 'count'
if apply_cardinality_reduction_pass:
cardinal_features_pass = high_cardinality_features
else:
cardinal_features_pass = []
#display dtypes
if supervised is False:
display_types_pass = True
else:
display_types_pass = False
#import library
from pycaret import preprocess
X = preprocess.Preprocess_Path_Two(train_data = data_for_preprocess,
categorical_features = cat_features_pass,
apply_ordinal_encoding = apply_ordinal_encoding_pass, #new
ordinal_columns_and_categories = ordinal_columns_and_categories_pass,
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,
display_types = display_types_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,
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_multicollinearity = remove_multicollinearity, #new
maximum_correlation_between_features = multicollinearity_threshold, #new
apply_grouping = apply_grouping_pass, #new
features_to_group_ListofList = group_features_pass, #new
group_name = group_names_pass, #new
random_state = seed)
progress.value += 1
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
prep_param = preprocess
#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
else:
transformation_grid = 'None'
if pca is True:
pca_method_grid = pca_method
else:
pca_method_grid = 'None'
if pca is True:
pca_components_grid = pca_components_pass
else:
pca_components_grid = 'None'
if combine_rare_levels:
rare_level_threshold_grid = rare_level_threshold
else:
rare_level_threshold_grid = 'None'
if bin_numeric_features is None:
numeric_bin_grid = False
else:
numeric_bin_grid = True
if ordinal_features is not None:
ordinal_features_grid = True
else:
ordinal_features_grid = False
if remove_multicollinearity is False:
multicollinearity_threshold_grid = None
else:
multicollinearity_threshold_grid = multicollinearity_threshold
if group_features is not None:
group_features_grid = True
else:
group_features_grid = False
if high_cardinality_features is not None:
high_cardinality_features_grid = True
else:
high_cardinality_features_grid = False
learned_types = preprocess.dtypes.learent_dtypes
#learned_types.drop(target, inplace=True)
float_type = 0
cat_type = 0
for i in preprocess.dtypes.learent_dtypes:
if 'float' in str(i):
float_type += 1
elif 'object' in str(i):
cat_type += 1
elif 'int' in str(i):
float_type += 1
"""
preprocessing ends here
"""
#reset pandas option
pd.reset_option("display.max_rows")
pd.reset_option("display.max_columns")
#create an empty list for pickling later.
if supervised is False:
experiment__ = []
else:
try:
experiment__.append('dummy')
experiment__.remove('dummy')
except:
experiment__ = []
progress.value += 1
#monitor update
monitor.iloc[1,1:] = 'Compiling Results'
if verbose:
update_display(monitor, display_id = 'monitor')
'''
Final display Starts
'''
shape = data.shape
shape_transformed = X.shape
functions = pd.DataFrame ( [ ['session_id ', seed ],
['Original Data ', shape ],
['Missing Values ', missing_flag],
['Numeric Features ', str(float_type-1) ],
['Categorical Features ', str(cat_type) ],
['Ordinal Features ', ordinal_features_grid],
['High Cardinality Features ', high_cardinality_features_grid],
['Transformed Data ', shape_transformed ],
['Numeric Imputer ', numeric_imputation],
['Categorical Imputer ', categorical_imputation],
['Normalize ', normalize ],
['Normalize Method ', normalize_grid ],
['Transformation ', transformation ],
['Transformation Method ', transformation_grid ],
['PCA ', pca],
['PCA Method ', pca_method_grid],
['PCA components ', pca_components_grid],
['Ignore Low Variance ', ignore_low_variance],
['Combine Rare Levels ', combine_rare_levels],
['Rare Level Threshold ', rare_level_threshold_grid],
['Numeric Binning ', numeric_bin_grid],
['Remove Multicollinearity ', remove_multicollinearity],
['Multicollinearity Threshold ', multicollinearity_threshold_grid],
['Group Features ', group_features_grid],
], columns = ['Description', 'Value'] )
functions_ = functions.style.apply(highlight_max)
progress.value += 1
if verbose:
if profile:
clear_output()
print('')
print('Setup Succesfully Completed! Loading Profile Now... Please Wait!')
display(functions_)
else:
clear_output()
print('')
print('Setup Succesfully Completed!')
display(functions_)
if profile:
try:
import pandas_profiling
pf = pandas_profiling.ProfileReport(data_before_preprocess)
clear_output()
display(pf)
except:
print('Data Profiler Failed. No output to show, please continue with Modeling.')
'''
Final display Ends
'''
#log into experiment
if verbose:
experiment__.append(('Anomaly Setup Config', functions))
experiment__.append(('Orignal Dataset', data_))
experiment__.append(('Transformed Dataset', X))
experiment__.append(('Transformation Pipeline', prep_pipe))
return X, data_, seed, prep_pipe, prep_param, experiment__
def create_model(model = None,
fraction = 0.05,
verbose = True):
"""
Description:
------------
This function creates a model on the dataset passed as a data param during
the setup stage. setup() function must be called before using create_model().
This function returns a trained model object.
Example
-------
from pycaret.datasets import get_data
anomaly = get_data('anomaly')
experiment_name = setup(data = anomaly, normalize = True)
knn = create_model('knn')
This will return trained k-Nearest Neighbors model.
Parameters
----------
model : string, default = None
Enter abbreviated string of the model class. List of available models supported:
Model Abbreviated String Original Implementation
--------- ------------------ -----------------------
Angle-base Outlier Detection 'abod' pyod.models.abod.ABOD
Isolation Forest 'iforest' module-pyod.models.iforest
Clustering-Based Local Outlier 'cluster' pyod.models.cblof
Connectivity-Based Outlier Factor 'cof' module-pyod.models.cof
Histogram-based Outlier Detection 'histogram' module-pyod.models.hbos
k-Nearest Neighbors Detector 'knn' module-pyod.models.knn
Local Outlier Factor 'lof' module-pyod.models.lof
One-class SVM detector 'svm' module-pyod.models.ocsvm
Principal Component Analysis 'pca' module-pyod.models.pca
Minimum Covariance Determinant 'mcd' module-pyod.models.mcd
Subspace Outlier Detection 'sod' module-pyod.models.sod
Stochastic Outlier Selection 'sos' module-pyod.models.sos
fraction: float, default = 0.05
The percentage / proportion of outliers in the dataset.
verbose: Boolean, default = True
Status update is not printed when verbose is set to False.
Returns:
--------
model: trained model object
------
Warnings:
---------
None
"""
#testing
#no test available
#exception checking
import sys
#ignore warings
import warnings
warnings.filterwarnings('ignore')
"""
error handling starts here
"""
#checking for model parameter
if model is None:
sys.exit('(Value Error): Model parameter Missing. Please see docstring for list of available models.')
#checking for allowed models
allowed_models = ['abod', 'iforest', 'cluster', 'cof', 'histogram', 'knn', 'lof', 'svm', 'pca', 'mcd', 'sod', 'sos']
if model not in allowed_models:
sys.exit('(Value Error): Model Not Available. Please see docstring for list of available models.')
#checking fraction type:
if type(fraction) is not float:
sys.exit('(Type Error): Fraction parameter can only take value as float between 0 to 1.')
#checking verbose parameter
if type(verbose) is not bool:
sys.exit('(Type Error): Verbose parameter can only take argument as True or False.')
"""
error handling ends here
"""
#pre-load libraries