forked from pycaret/pycaret
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclustering.py
1827 lines (1282 loc) · 58.1 KB
/
clustering.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
def setup(data,
session_id = None,
normalize = False,
verbose=True):
"""
Description:
------------
This function initialize the environment in pycaret. setup() must called before
executing any other function in pycaret. It takes one mandatory parameters i.e.
dataframe {array-like, sparse matrix}.
Example
-------
experiment_name = setup(data)
data 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 or object of type
list with n length.
session_id: int, default = None
If None, random seed is generated and returned in Information grid. The unique number
is then distributed as a seed in all other functions used during experiment. This can
be used later for reproducibility of entire experiment.
normalize: bool, default = False
scaling of feature set using MinMaxScaler. by default normalize 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 being used by other functions in pycaret.
Warnings:
---------
- None
"""
#exception checking
import sys
#ignore warnings
import warnings
warnings.filterwarnings('ignore')
"""
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.')
"""
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
'''
generate monitor starts
'''
#progress bar
max_steps = 3
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')
'''
generate monitor end
'''
#general dependencies
import numpy as np
import pandas as pd
import random
#defining global variables
global X, data_, experiment__, seed
#copying data
data_ = data.copy()
#create an empty list for pickling later.
try:
experiment__.append('dummy')
experiment__.pop()
except:
experiment__ = []
#generate seed to be used globally
if session_id is None:
seed = random.randint(150,9000)
else:
seed = session_id
progress.value += 1
#monitor update
monitor.iloc[1,1:] = 'Scaling the Data'
if verbose:
update_display(monitor, display_id = 'monitor')
#scaling
if normalize:
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
X = pd.get_dummies(data_)
scaler = scaler.fit(X)
#append to experiment__
experiment__.append(('Scaler',scaler))
X = scaler.transform(X)
X = pd.DataFrame(X)
else:
X = data_.copy()
X = pd.get_dummies(data_)
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
if normalize:
scaling = 'True'
else:
scaling = 'False'
functions = pd.DataFrame ( [ ['session_id', seed ],
['Scaling', scaling],
['Shape', shape ],
], columns = ['Description', 'Value'] )
functions_ = functions.style.hide_index()
progress.value += 1
if verbose:
clear_output()
display(functions_)
'''
Final display Ends
'''
#log into experiment
if verbose:
experiment__.append(('Clustering Info', functions))
experiment__.append(('Dataset', data_))
experiment__.append(('Normalized Dataset', X))
return X, data_, seed, experiment__
def create_model(model = None,
num_clusters = None,
verbose=True):
"""
Description:
------------
This function creates a model using training data passed during setup stage.
Hence dataset doesn't need to be specified during create_model. This Function
returns trained model object can then be used for inference the training data
or new unseen data.
setup() function must be called before using create_model()
Example
-------
knn = create_model('kmeans')
This will return trained K-Means clustering model.
Parameters
----------
model : string, default = None
Enter abbreviated string of the model class. List of model supported:
Model Abbreviated String Original Implementation
--------- ------------------ -----------------------
K-Means clustering 'kmeans' sklearn.cluster.KMeans.html
Affinity Propagation 'ap' AffinityPropagation.html
Mean shift clustering 'meanshift' sklearn.cluster.MeanShift.html
Spectral Clustering 'sc' SpectralClustering.html
Agglomerative Clustering 'hclust' AgglomerativeClustering.html
Density-Based Spatial Clustering 'dbscan' sklearn.cluster.DBSCAN.html
OPTICS Clustering 'optics' sklearn.cluster.OPTICS.html
Birch Clustering 'birch' sklearn.cluster.Birch.html
K-Modes clustering 'kmodes' git/nicodv/kmodes
Spherical K-Means clustering 'skmeans' git/jasonlaska/spherecluster
num_clusters: int, default = None
Number of clusters to be made in the dataset. if None num_clusters is set to 4.
verbose: Boolean, default = True
Status update is not printed when verbose is set to False.
Returns:
--------
model: trained model object
------
Warnings:
---------
- num_clusters not required for Affinity Propagation, Mean shift clustering,
Density-Based Spatial Clustering and OPTICS Clustering. num_clusters is
automatically determined.
- OPTICS ('optics') clustering may take longer training times on large datasets.
"""
#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 = ['kmeans', 'ap', 'meanshift', 'sc', 'hclust', 'dbscan', 'optics', 'birch', 'kmodes', 'skmeans']
#check num_clusters parameter:
if num_clusters is not None:
no_num_required = ['ap', 'meanshift', 'dbscan', 'optics']
if model in no_num_required:
sys.exit('(Value Error): num_clusters parameter not required for specified model. Remove num_clusters to run this model.')
if model not in allowed_models:
sys.exit('(Value Error): Model Not Available. Please see docstring for list of available models.')
#checking num_clusters type:
if num_clusters is not None:
if type(num_clusters) is not int:
sys.exit('(Type Error): num_clusters parameter can only take value integer value greater than 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
import pandas as pd
import ipywidgets as ipw
from IPython.display import display, HTML, clear_output, update_display
import datetime, time
#determine num_clusters
if num_clusters is None:
num_clusters = 4
else:
num_clusters = num_clusters
"""
monitor starts
"""
#progress bar and monitor control
timestampStr = datetime.datetime.now().strftime("%H:%M:%S")
progress = ipw.IntProgress(value=0, min=0, max=3, step=1 , description='Processing: ')
monitor = pd.DataFrame( [ ['Initiated' , '. . . . . . . . . . . . . . . . . .', timestampStr ],
['Status' , '. . . . . . . . . . . . . . . . . .' , 'Initializing'] ],
columns=['', ' ', ' ']).set_index('')
if verbose:
display(progress)
display(monitor, display_id = 'monitor')
progress.value += 1
"""
monitor ends
"""
if model == 'kmeans':
from sklearn.cluster import KMeans
model = KMeans(n_clusters = num_clusters, random_state=seed)
full_name = 'K-Means Clustering'
elif model == 'ap':
from sklearn.cluster import AffinityPropagation
model = AffinityPropagation(damping=0.5)
full_name = 'Affinity Propagation'
elif model == 'meanshift':
from sklearn.cluster import MeanShift
model = MeanShift()
full_name = 'Mean Shift Clustering'
elif model == 'sc':
from sklearn.cluster import SpectralClustering
model = SpectralClustering(n_clusters=num_clusters, random_state=seed, n_jobs=-1)
full_name = 'Spectral Clustering'
elif model == 'hclust':
from sklearn.cluster import AgglomerativeClustering
model = AgglomerativeClustering(n_clusters=num_clusters)
full_name = 'Agglomerative Clustering'
elif model == 'dbscan':
from sklearn.cluster import DBSCAN
model = DBSCAN(eps=0.5, n_jobs=-1)
full_name = 'Density-Based Spatial Clustering'
elif model == 'optics':
from sklearn.cluster import OPTICS
model = OPTICS(n_jobs=-1)
full_name = 'OPTICS Clustering'
elif model == 'birch':
from sklearn.cluster import Birch
model = Birch(n_clusters=num_clusters)
full_name = 'Birch Clustering'
elif model == 'kmodes':
from kmodes.kmodes import KModes
model = KModes(n_clusters=num_clusters, n_jobs=1, random_state=seed)
full_name = 'K-Modes Clustering'
elif model == 'skmeans':
from spherecluster import SphericalKMeans
model = SphericalKMeans(n_clusters=num_clusters, n_jobs=1, random_state=seed)
full_name = 'Spherical K-Means Clustering'
#monitor update
monitor.iloc[1,1:] = 'Fitting ' + str(full_name) + ' Model'
progress.value += 1
if verbose:
update_display(monitor, display_id = 'monitor')
#fitting the model
model.fit(X)
#storing in experiment__
if verbose:
tup = (full_name,model)
experiment__.append(tup)
progress.value += 1
if verbose:
clear_output()
return model
def assign_model(model,
verbose=True):
"""
Description:
------------
This function is used for inference of clusters on training data passed in setup
function using trained model created using create_model function. The function
returns dataframe with assigned clusters by instance.
create_model() function must be called before using assign_model()
Example
-------
kmeans = create_model('kmeans')
kmeans_df = assign_model(kmeans)
This will return dataframe with inferred clusters using trained model passed
as model param.
Parameters
----------
model : trained model object, default = None
verbose: Boolean, default = True
Status update is not printed when verbose is set to False.
Returns:
--------
dataframe: Returns dataframe with assigned clusters using trained model.
---------
Warnings:
---------
None
"""
#exception checking
import sys
#ignore warnings
import warnings
warnings.filterwarnings('ignore')
"""
error handling starts here
"""
#determine model type and store in string
mod_type = str(type(model))
#checking for allowed models
if 'sklearn' not in mod_type and 'KModes' not in mod_type and 'SphericalKMeans' not in mod_type:
sys.exit('(Value Error): Model Not Recognized. Please see docstring for list of available models.')
#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
import numpy as np
import pandas as pd
import ipywidgets as ipw
from IPython.display import display, HTML, clear_output, update_display
import datetime, time
#copy data_
data__ = data_.copy()
#progress bar and monitor control
timestampStr = datetime.datetime.now().strftime("%H:%M:%S")
progress = ipw.IntProgress(value=0, min=0, max=3, step=1 , description='Processing: ')
monitor = pd.DataFrame( [ ['Initiated' , '. . . . . . . . . . . . . . . . . .', timestampStr ],
['Status' , '. . . . . . . . . . . . . . . . . .' , 'Initializing'] ],
columns=['', ' ', ' ']).set_index('')
if verbose:
display(progress)
display(monitor, display_id = 'monitor')
progress.value += 1
monitor.iloc[1,1:] = 'Inferring Clusters from Model'
if verbose:
update_display(monitor, display_id = 'monitor')
progress.value += 1
#calculation labels and attaching to dataframe
labels = []
for i in model.labels_:
a = 'Cluster ' + str(i)
labels.append(a)
data__['Cluster'] = labels
progress.value += 1
name_ = mod_type + ' Clustering'
#storing in experiment__
if verbose:
tup = (name_,data__)
experiment__.append(tup)
if verbose:
clear_output()
return data__
def tune_model(model=None,
supervised_target=None,
estimator=None,
optimize=None,
fold=10):
"""
Description:
------------
This function tunes the num_clusters model parameter using predefined diverse grid
with objective to optimize supervised learning metric as defined in optimize param.
This function cannot be used unsupervised. It allows to select estimator from a large
library available in pycaret. By default supervised estimator is Linear.
This function returns the num_clusters param that are considered best using optimize
param.
setup() function must be called prior to using this function.
Example
-------
tuned_kmeans = tune_model('kmeans', supervised_target = 'medv', optimize='R2')
This will return trained K Means Clustering Model with num_clusters param
that is optimized to improve 'R2' as defined in optimize param. By
default optimize param is 'Accuracy' for classification tasks and 'R2' for
regression tasks. Task is determined automatically based on supervised_target
param.
Parameters
----------
model : string, default = None
Enter abbreviated name of the model. List of available models supported:
Model Abbreviated String Original Implementation
--------- ------------------ -----------------------
K-Means clustering 'kmeans' sklearn.cluster.KMeans.html
Spectral Clustering 'sc' SpectralClustering.html
Agglomerative Clustering 'hclust' AgglomerativeClustering.html
Birch Clustering 'birch' sklearn.cluster.Birch.html
K-Modes clustering 'kmodes' git/nicodv/kmodes
Spherical K-Means clustering 'skmeans' git/jasonlaska/spherecluster
supervised_target: string
Name of target column for supervised learning. It cannot be None.
estimator: string, default = None
Estimator Abbreviated String Task
--------- ------------------ ---------------
Logistic Regression 'lr' Classification
K Nearest Neighbour 'knn' Classification
Naives Bayes 'nb' Classification
Decision Tree 'dt' Classification
SVM (Linear) 'svm' Classification
SVM (RBF) 'rbfsvm' Classification
Gaussian Process 'gpc' Classification
Multi Level Perceptron 'mlp' Classification
Ridge Classifier 'ridge' Classification
Random Forest 'rf' Classification
Quadratic Disc. Analysis 'qda' Classification
AdaBoost 'ada' Classification
Gradient Boosting 'gbc' Classification
Linear Disc. Analysis 'lda' Classification
Extra Trees Classifier 'et' Classification
Extreme Gradient Boosting 'xgboost' Classification
Light Gradient Boosting 'lightgbm' Classification
CatBoost Classifier 'catboost' Classification
Linear Regression 'lr' Regression
Lasso Regression 'lasso' Regression
Ridge Regression 'ridge' Regression
Elastic Net 'en' Regression
Least Angle Regression 'lar' Regression
Lasso Least Angle Regression 'llar' Regression
Orthogonal Matching Pursuit 'omp' Regression
Bayesian Ridge 'br' Regression
Automatic Relevance Determ. 'ard' Regression
Passive Aggressive Regressor 'par' Regression
Random Sample Consensus 'ransac' Regression
TheilSen Regressor 'tr' Regression
Huber Regressor 'huber' Regression
Kernel Ridge 'kr' Regression
Support Vector Machine 'svm' Regression
K Neighbors Regressor 'knn' Regression
Decision Tree 'dt' Regression
Random Forest 'rf' Regression
Extra Trees Regressor 'et' Regression
AdaBoost Regressor 'ada' Regression
Gradient Boosting 'gbr' Regression
Multi Level Perceptron 'mlp' Regression
Extreme Gradient Boosting 'xgboost' Regression
Light Gradient Boosting 'lightgbm' Regression
CatBoost Classifier 'catboost' Regression
If set to None, by default Linear model is used for both classification
and regression tasks.
optimize: string, default = None
For Classification tasks:
Accuracy, AUC, Recall, Precision, F1, Kappa
For Regression tasks:
MAE, MSE, RMSE, R2, ME
If set to None, default is 'Accuracy' for classification and 'R2' for
regression tasks.
fold: integer, default = 10
Number of folds to be used in Kfold CV. Must be at least 2.
Returns:
--------
visual plot: Visual plot with num_clusters param on x-axis with metric to
----------- optimize on y-axis. Also, prints the best model metric.
model: trained model object with best num_clusters param.
-----------
Warnings:
---------
- Affinity Propagation, Mean shift clustering, Density-Based Spatial Clustering
and OPTICS Clustering cannot be used in this module since they donot support
num_clusters param.
"""
"""
exception handling starts here
"""
#testing
global master_df, sorted_df, ival, master
#ignore warnings
import warnings
warnings.filterwarnings('ignore')
import sys
#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 = ['kmeans', 'sc', 'hclust', 'birch', 'kmodes', 'skmeans']
if model not in allowed_models:
sys.exit('(Value Error): Model Not Available for Tuning. Please see docstring for list of available models.')
#check if supervised target is None:
if supervised_target is None:
sys.exit('(Value Error): supervised_target cannot be None. A column name must be given for estimator.')
#check supervised target:
if supervised_target is not None:
all_col = list(data_.columns)
#target = str(supervised_target)
#all_col.remove(target)
if supervised_target not in all_col:
sys.exit('(Value Error): supervised_target not recognized. It can only be one of the following: ' + str(all_col))
#checking estimator:
if estimator is not None:
available_estimators = ['lr', 'knn', 'nb', 'dt', 'svm', 'rbfsvm', 'gpc', 'mlp', 'ridge', 'rf', 'qda', 'ada',
'gbc', 'lda', 'et', 'lasso', 'ridge', 'en', 'lar', 'llar', 'omp', 'br', 'ard', 'par',
'ransac', 'tr', 'huber', 'kr', 'svm', 'knn', 'dt', 'rf', 'et', 'ada', 'gbr',
'mlp', 'xgboost', 'lightgbm', 'catboost']
if estimator not in available_estimators:
sys.exit('(Value Error): Estimator Not Available. Please see docstring for list of available estimators.')
#checking optimize parameter
if optimize is not None:
available_optimizers = ['MAE', 'MSE', 'RMSE', 'R2', 'ME', 'Accuracy', 'AUC', 'Recall', 'Precision', 'F1', 'Kappa']
if optimize not in available_optimizers:
sys.exit('(Value Error): optimize parameter Not Available. Please see docstring for list of available parameters.')
#checking fold parameter
if type(fold) is not int:
sys.exit('(Type Error): Fold parameter only accepts integer value.')
"""
exception 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
#progress bar
max_steps = 25
progress = ipw.IntProgress(value=0, min=0, max=max_steps, step=1 , description='Processing: ')
display(progress)
timestampStr = datetime.datetime.now().strftime("%H:%M:%S")
monitor = pd.DataFrame( [ ['Initiated' , '. . . . . . . . . . . . . . . . . .', timestampStr ],
['Status' , '. . . . . . . . . . . . . . . . . .' , 'Loading Dependencies'],
['Step' , '. . . . . . . . . . . . . . . . . .', 'Initializing' ] ],
columns=['', ' ', ' ']).set_index('')
display(monitor, display_id = 'monitor')
#General Dependencies
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_predict
from sklearn import metrics
import numpy as np
import plotly.express as px
#from sklearn.preprocessing import MinMaxScaler
#scaler = MinMaxScaler()
#setting up cufflinks
import cufflinks as cf
cf.go_offline()
cf.set_config_file(offline=False, world_readable=True)
progress.value += 1
#define the problem
if data_[supervised_target].value_counts().count() == 2:
problem = 'classification'
else:
problem = 'regression'
#define model name
if model == 'kmeans':
model_name = 'K-Means Clustering'
elif model == 'ap':
model_name = 'Affinity Propagation'
elif model == 'meanshift':
model_name = 'Mean Shift Clustering'
elif model == 'sc':
model_name = 'Spectral Clustering'
elif model == 'hclust':
model_name = 'Agglomerative Clustering'
elif model == 'dbscan':
model_name = 'Density-Based Spatial Clustering'
elif model == 'optics':
model_name = 'OPTICS Clustering'
elif model == 'birch':
model_name = 'Birch Clustering'
elif model == 'kmodes':
model_name = 'K-Modes Clustering'
elif model == 'skmeans':
model_name = 'Spherical K-Means Clustering'
#defining estimator:
if problem == 'classification' and estimator is None:
estimator = 'lr'
elif problem == 'regression' and estimator is None:
estimator = 'lr'
else:
estimator = estimator
#defining optimizer:
if optimize is None and problem == 'classification':
optimize = 'Accuracy'
elif optimize is None and problem == 'regression':
optimize = 'R2'
else:
optimize=optimize
progress.value += 1
#defining tuning grid
param_grid_with_zero = [0, 4, 5, 6, 8, 10, 14, 18, 25, 30, 40]
param_grid = [4, 5, 6, 8, 10, 14, 18, 25, 30, 40]
master = []; master_df = []
monitor.iloc[1,1:] = 'Creating Clustering Model'
update_display(monitor, display_id = 'monitor')
#removing target variable from data by defining new setup
target_ = pd.DataFrame(data_[supervised_target])
data_without_target = data_.copy()
data_without_target.drop([supervised_target], axis=1, inplace=True)
setup_without_target = setup(data_without_target, verbose=False, session_id=seed)
#adding dummy model in master
master.append('No Model Required')
master_df.append('No Model Required')
for i in param_grid:
progress.value += 1
monitor.iloc[2,1:] = 'Fitting Model With ' + str(i) + ' Clusters'
update_display(monitor, display_id = 'monitor')
#create and assign the model to dataset d
m = create_model(model=model, num_clusters=i, verbose=False)
d = assign_model(m, verbose=False)
d[str(supervised_target)] = target_
master.append(m)
master_df.append(d)
#clustering model creation end's here
#attaching target variable back
data_[str(supervised_target)] = target_
if problem == 'classification':
"""
defining estimator
"""
monitor.iloc[1,1:] = 'Evaluating Clustering Model'
update_display(monitor, display_id = 'monitor')
if estimator == 'lr':
from sklearn.linear_model import LogisticRegression
model = LogisticRegression(random_state=seed)
full_name = 'Logistic Regression'
elif estimator == 'knn':
from sklearn.neighbors import KNeighborsClassifier
model = KNeighborsClassifier()
full_name = 'K Nearest Neighbours'
elif estimator == 'nb':
from sklearn.naive_bayes import GaussianNB
model = GaussianNB()
full_name = 'Naive Bayes'
elif estimator == 'dt':
from sklearn.tree import DecisionTreeClassifier
model = DecisionTreeClassifier(random_state=seed)
full_name = 'Decision Tree'
elif estimator == 'svm':
from sklearn.linear_model import SGDClassifier
model = SGDClassifier(max_iter=1000, tol=0.001, random_state=seed)
full_name = 'Support Vector Machine'
elif estimator == 'rbfsvm':
from sklearn.svm import SVC
model = SVC(gamma='auto', C=1, probability=True, kernel='rbf', random_state=seed)
full_name = 'RBF SVM'
elif estimator == 'gpc':
from sklearn.gaussian_process import GaussianProcessClassifier
model = GaussianProcessClassifier(random_state=seed)
full_name = 'Gaussian Process Classifier'
elif estimator == 'mlp':
from sklearn.neural_network import MLPClassifier
model = MLPClassifier(max_iter=500, random_state=seed)
full_name = 'Multi Level Perceptron'
elif estimator == 'ridge':
from sklearn.linear_model import RidgeClassifier
model = RidgeClassifier(random_state=seed)
full_name = 'Ridge Classifier'
elif estimator == 'rf':
from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(n_estimators=10, random_state=seed)
full_name = 'Random Forest Classifier'
elif estimator == 'qda':
from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis
model = QuadraticDiscriminantAnalysis()
full_name = 'Quadratic Discriminant Analysis'
elif estimator == 'ada':
from sklearn.ensemble import AdaBoostClassifier
model = AdaBoostClassifier(random_state=seed)
full_name = 'AdaBoost Classifier'
elif estimator == 'gbc':
from sklearn.ensemble import GradientBoostingClassifier
model = GradientBoostingClassifier(random_state=seed)
full_name = 'Gradient Boosting Classifier'
elif estimator == 'lda':
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
model = LinearDiscriminantAnalysis()
full_name = 'Linear Discriminant Analysis'
elif estimator == 'et':
from sklearn.ensemble import ExtraTreesClassifier
model = ExtraTreesClassifier(random_state=seed)
full_name = 'Extra Trees Classifier'
elif estimator == 'xgboost':
from xgboost import XGBClassifier
model = XGBClassifier(random_state=seed, n_jobs=-1, verbosity=0)
full_name = 'Extreme Gradient Boosting'
elif estimator == 'lightgbm':
import lightgbm as lgb
model = lgb.LGBMClassifier(random_state=seed)
full_name = 'Light Gradient Boosting Machine'
elif estimator == 'catboost':
from catboost import CatBoostClassifier
model = CatBoostClassifier(random_state=seed, silent=True) # Silent is True to suppress CatBoost iteration results
full_name = 'CatBoost Classifier'
progress.value += 1
"""
start model building here
"""
acc = []; auc = []; recall = []; prec = []; kappa = []; f1 = []
#build model without clustering
monitor.iloc[2,1:] = 'Evaluating Classifier Without Clustering'