forked from sudarsun/ams
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gen_indices.py
891 lines (704 loc) · 31.6 KB
/
gen_indices.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
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
warnings.filterwarnings("ignore", category=DeprecationWarning)
import sys
import eda
import internal_indices
import external_indices
import os
import pickle
def kmeans_indices(sampled_data):
# name of folder which contains the dataset's (randomly sampled) bag and metadata files.
'''Parameters for K-Means Cluster Analysis'''
# Method used to determine the number of clusters in data for K-Means Clustering.
kmeans_n_clusters = 'gap' # Use gap statistics to estimate the optimal number of clusters from data (default)
kmeans_kargs = {} # Other Keyword arguments (other than 'n_clusters') to :func:`sklearn.cluster.KMeans`
""" Code to perform cluster analysis and Validation
Note: Not to be modified by the user
"""
internal_indices_functions = {
'WGSS':'wgss_index',
'BGSS':'bgss_index',
'Ball-Hall':'ball_hall_index',
'Banfeld-Raftery':'banfeld_raftery_index',
'Det-Ratio':'det_ratio_index',
'Ksq-DetW':'ksq_detw_index',
'Log-Det-Ratio':'log_det_ratio_index',
'Log-SS-Ratio':'log_ss_ratio_index',
'Scott-Symons':'scott_symons_index',
'Trace-WiB':'trace_wib_index',
'Silhouette':'silhouette_score',
'Calinski-Harabasz':'calinski_harabaz_score',
'C':'c_index',
'Dunn':'dunn_index',
'Davies-Bouldin':'davies_bouldin_index',
'Ray-Turi':'ray_turi_index',
'Hartigan':'hartigan_index',
'PBM':'pbm_index',
'Score':'score_function'
}
# Note: Strictly don't modify (or reorder) the 'choosen_internal_indices' list (without corresponding changes to 'results.csv' in warehouse)
choosen_internal_indices = [
'WGSS',
'BGSS',
'Ball-Hall',
'Banfeld-Raftery',
'Calinski-Harabasz',
'Det-Ratio',
'Ksq-DetW',
'Log-Det-Ratio',
'Log-SS-Ratio',
#'Scott-Symons',
'Silhouette',
'Trace-WiB',
'C',
'Dunn',
'Davies-Bouldin',
'Ray-Turi',
'PBM',
'Score'
]
# TODO*: Check if Sklearn's Precision, Recall, ... which are for classification work for clustering as well (change cluster indices and observe change in precision)
external_indices_functions = {
'Entropy':'entropy',
'Purity':'purity',
'Precision':'precision_coefficient',
'Recall':'recall_coefficient',
'F':'f_measure',
'Weighted-F':'weighted_f_measure',
'Folkes-Mallows':'folkes_mallows_index',
'Rand':'rand_index',
'Adjusted-Rand':'adjusted_rand_index',
'Adjusted-Mutual-Info':'adjusted_mutual_info',
'Normalised-Mutual-Info':'normalized_mutual_info',
'Homegeneity':'homogeneity_score',
'Completeness':'completness_score',
'V-Measure':'v_measure_score',
'Jaccard':'jaccard_coeff',
'Hubert Γ̂':'hubert_T_index',
'Kulczynski':'kulczynski_index',
'McNemar':'mcnemar_index',
'Phi':'phi_index',
'Russel-Rao':'russel_rao_index',
'Rogers-Tanimoto':'rogers_tanimoto_index',
'Sokal-Sneath1':'sokal_sneath_index1',
'Sokal-Sneath2':'sokal_sneath_index2'
}
# Note: Strictly don't modify (or reorder) the 'choosen_external_indices' list (without corresponding changes to 'results.csv' in warehouse)
choosen_external_indices = [
'Entropy',
'Purity',
'Precision',
'Recall',
'F',
'Weighted-F',
'Folkes-Mallows',
'Rand',
'Adjusted-Rand',
'Adjusted-Mutual-Info',
'Normalised-Mutual-Info',
'Homegeneity',
'Completeness',
'V-Measure',
'Jaccard',
'Hubert Γ̂',
'Kulczynski',
'McNemar',
'Phi',
'Russel-Rao',
'Rogers-Tanimoto',
'Sokal-Sneath1',
'Sokal-Sneath2'
]
bag_name = sampled_data[0]['dataset_name'].split('.')[0]
curr_pwd = str(os.getcwd())
indices_pwd = curr_pwd + '/indices/'
os.chdir(indices_pwd)
file_name_indices = bag_name+"kmeans_indices.csv"
# Open 'results.csv' file in warehouse and append all results to it.
results_file = open(file_name_indices, 'a')
n_bags = len(sampled_data)
# Preprocess the 'kmeans_n_clusters' argument to standard accepted forms
if isinstance(kmeans_n_clusters, str) and kmeans_n_clusters in ['gap', 'n_classes']:
kmeans_n_clusters = [kmeans_n_clusters] * n_bags
elif isinstance(kmeans_n_clusters, int):
kmeans_n_clusters = [kmeans_n_clusters] * n_bags
elif isinstance(kmeans_n_clusters, list):
if len(kmeans_n_clusters)!=n_bags:
print("error: The length of 'kmeans_n_clusters' list supplied doesn't match the count of the number of bags")
sys.exit(1)
for bag_n_cluster in kmeans_n_clusters:
if isinstance(bag_n_cluster, int):
pass
elif isinstance(bag_n_cluster, 'str') and bag_n_cluster in ['gap','n_classes']:
pass
else:
print("error: invalid entry %s in list supplied as argument to parameter 'kmeans_n_clusters'"%bag_n_cluster.__repr__())
sys.exit()
else:
print("error: invalid argument to parameter 'kmeans_n_clusters'. Accepted arguments: {'gap', 'n_classes', <int>, <list of {int,'gap','n_classes'} of shape (n_bags,)> }")
tot_cluster_result =[]
for x in range(len(sampled_data)):
print("Processing '{file_name}'".format(file_name=bag_name+"_bag_"+str(sampled_data[x]['bag_number'])))
dataset = sampled_data[x]
data, target = dataset['data'], dataset['target']
# Load the data into an eda object :obj:`main`
main = eda.eda()
main.load_data(data, target)
# perform kmeans clustering on the data
main.perform_kmeans(n_clusters=kmeans_n_clusters[x], **kmeans_kargs)
# Compute the internal indices for K-Means Clustering Results
kmeans_internal_validation = internal_indices.internal_indices(main.data, main.kmeans_results['labels'])
kmeans_internal_indices = []
for index in choosen_internal_indices:
index_function = getattr(kmeans_internal_validation, internal_indices_functions[index])
print("Computing Internal Indices (KMeans Clustering): %s Index"%index)
kmeans_internal_indices.append(index_function())
# Compute the external indices for K-Means Clustering Results
kmeans_external_validation = external_indices.external_indices(main.target, main.kmeans_results['labels'])
kmeans_external_indices = []
for index in choosen_external_indices:
index_function = getattr(kmeans_external_validation, external_indices_functions[index])
print("Computing External Indices (KMeans Clustering): %s Index"%index)
kmeans_external_indices.append(index_function())
# Print the KMeans Clustering results to a 'results.csv' in warehouse
results_file.write("\"{file_name}\",\"{bag_num}\",{sample_size},\"{algorithm}\",\"{parameters}\",{n_clusters},\"{cluster_distrn}\",".format(file_name=bag_name,bag_num=sampled_data[x]['bag_number'], sample_size=main.n_samples, algorithm='KMeans', parameters=main.kmeans_results['parameters'].__repr__(), n_clusters=main.kmeans_results['n_clusters'], cluster_distrn=main.kmeans_results['clusters'].__repr__()))
for index in kmeans_internal_indices:
results_file.write("{},".format(index))
for index in kmeans_external_indices:
results_file.write("{},".format(index))
results_file.write('\n')
cluster_result = {
"file_name":bag_name,
"bag_num":sampled_data[x]['bag_number'],
"sample_size":main.n_samples,
"algorithm":'KMeans',
"parameters":main.kmeans_results['parameters'].__repr__(),
"n_clusters":main.kmeans_results['n_clusters'],
"cluster_distrn":main.kmeans_results['clusters'].__repr__(),
"kmeans_internal_indices":kmeans_internal_indices,
"kmeans_external_indices":kmeans_external_indices
}
tot_cluster_result.append(cluster_result)
del main
os.chdir(curr_pwd)
return tot_cluster_result
def hierarchial_indices(sampled_data):
'''Parameters for Ward's Agglomerative Cluster Analysis'''
# Method used to determine the number of clusters in data for Hierarchial Clustering.
# Allowed arguments: {'gap', 'n_classes', <int>, <list of integers of shape (n_bags,)>}
hierarchial_n_clusters = 'gap' # Use gap statistics to estimate the optimal number of clusters from data (default)
hierarchial_kargs = {} # Other Keyword arguments (other than 'n_clusters') to :func:`sklearn.cluster.AgglomerativeClustering`
# Method used to determine the number of clusters in data for Hierarchial Clustering.
# Allowed arguments: {'gap', 'n_classes', <int>, <list of integers of shape (n_bags,)>}
spectral_n_clusters = 'gap' # Use gap statistics to estimate the optimal number of clusters from data (default)
spectral_kargs = {} # Other Keyword arguments (other than 'n_clusters') to :func:`sklearn.cluster.AgglomerativeClustering`
""" Code to perform cluster analysis and Validation
Note: Not to be modified by the user
"""
internal_indices_functions = {
'WGSS':'wgss_index',
'BGSS':'bgss_index',
'Ball-Hall':'ball_hall_index',
'Banfeld-Raftery':'banfeld_raftery_index',
'Det-Ratio':'det_ratio_index',
'Ksq-DetW':'ksq_detw_index',
'Log-Det-Ratio':'log_det_ratio_index',
'Log-SS-Ratio':'log_ss_ratio_index',
'Scott-Symons':'scott_symons_index',
'Trace-WiB':'trace_wib_index',
'Silhouette':'silhouette_score',
'Calinski-Harabasz':'calinski_harabaz_score',
'C':'c_index',
'Dunn':'dunn_index',
'Davies-Bouldin':'davies_bouldin_index',
'Ray-Turi':'ray_turi_index',
'Hartigan':'hartigan_index',
'PBM':'pbm_index',
'Score':'score_function'
}
# Note: Strictly don't modify (or reorder) the 'choosen_internal_indices' list (without corresponding changes to 'results.csv' in warehouse)
choosen_internal_indices = [
'WGSS', 'BGSS',
'Ball-Hall',
'Banfeld-Raftery',
'Calinski-Harabasz',
'Det-Ratio',
'Ksq-DetW',
'Log-Det-Ratio',
'Log-SS-Ratio',
#'Scott-Symons',
'Silhouette',
'Trace-WiB',
'C',
'Dunn',
'Davies-Bouldin',
'Ray-Turi',
'PBM',
'Score'
]
# TODO*: Check if Sklearn's Precision, Recall, ... which are for classification work for clustering as well (change cluster indices and observe change in precision)
external_indices_functions = {
'Entropy':'entropy',
'Purity':'purity',
'Precision':'precision_coefficient',
'Recall':'recall_coefficient',
'F':'f_measure',
'Weighted-F':'weighted_f_measure',
'Folkes-Mallows':'folkes_mallows_index',
'Rand':'rand_index',
'Adjusted-Rand':'adjusted_rand_index',
'Adjusted-Mutual-Info':'adjusted_mutual_info',
'Normalised-Mutual-Info':'normalized_mutual_info',
'Homegeneity':'homogeneity_score',
'Completeness':'completness_score',
'V-Measure':'v_measure_score',
'Jaccard':'jaccard_coeff',
'Hubert Γ̂':'hubert_T_index',
'Kulczynski':'kulczynski_index',
'McNemar':'mcnemar_index',
'Phi':'phi_index',
'Russel-Rao':'russel_rao_index',
'Rogers-Tanimoto':'rogers_tanimoto_index',
'Sokal-Sneath1':'sokal_sneath_index1',
'Sokal-Sneath2':'sokal_sneath_index2'
}
# Note: Strictly don't modify (or reorder) the 'choosen_external_indices' list (without corresponding changes to 'results.csv' in warehouse)
choosen_external_indices = [
'Entropy',
'Purity',
'Precision',
'Recall',
'F',
'Weighted-F',
'Folkes-Mallows',
'Rand',
'Adjusted-Rand',
'Adjusted-Mutual-Info',
'Normalised-Mutual-Info',
'Homegeneity',
'Completeness',
'V-Measure',
'Jaccard',
'Hubert Γ̂',
'Kulczynski',
'McNemar',
'Phi',
'Russel-Rao',
'Rogers-Tanimoto',
'Sokal-Sneath1',
'Sokal-Sneath2'
]
bag_name = sampled_data[0]['dataset_name'].split('.')[0]
curr_pwd = str(os.getcwd())
indices_pwd = curr_pwd + '/indices/'
os.chdir(indices_pwd)
file_name_indices = bag_name+"heirarchical_indices.csv"
# Open 'results.csv' file in warehouse and append all results to it.
results_file = open(file_name_indices, 'a')
n_bags = len(sampled_data)
# Preprocess the 'hierarchial_n_clusters' argument to standard accepted forms
if isinstance(hierarchial_n_clusters, str) and hierarchial_n_clusters in ['gap', 'n_classes']:
hierarchial_n_clusters = [hierarchial_n_clusters] * n_bags
elif isinstance(hierarchial_n_clusters, int):
hierarchial_n_clusters = [hierarchial_n_clusters] * n_bags
elif isinstance(hierarchial_n_clusters, list):
if len(hierarchial_n_clusters)!=n_bags:
print("error: The length of 'hierarchial_n_clusters' list supplied doesn't match the count of the number of bags")
sys.exit(1)
for bag_n_cluster in hierarchial_n_clusters:
if isinstance(bag_n_cluster, int):
pass
elif isinstance(bag_n_cluster, 'str') and bag_n_cluster in ['gap','n_classes']:
pass
else:
print("error: invalid entry %s in list supplied as argument to parameter 'hierarchial_n_clusters'"%bag_n_cluster.__repr__())
sys.exit()
else:
print("error: invalid argument to parameter 'hierarchial_n_clusters'. Accepted arguments: {'gap', 'n_classes', <int>, <list of {int,'gap','n_classes'} of shape (n_bags,)> }")
tot_cluster_result =[]
for x in range(len(sampled_data)):
print("Processing '{file_name}'".format(file_name=bag_name+"_bag_"+str(sampled_data[x]['bag_number'])))
dataset = sampled_data[x]
data, target = dataset['data'], dataset['target']
# Load the data into an eda object :obj:`main`
main = eda.eda()
main.load_data(data, target)
# perform kmeans clustering on the data
main.perform_hierarchial(n_clusters=hierarchial_n_clusters[x], **hierarchial_kargs)
# Compute the internal indices for K-Means Clustering Results
hierarchial_internal_validation = internal_indices.internal_indices(main.data, main.hierarchial_results['labels'])
hierarchial_internal_indices = []
for index in choosen_internal_indices:
index_function = getattr(hierarchial_internal_validation, internal_indices_functions[index])
print("Computing Internal Indices (hierarchial Clustering): %s Index"%index)
hierarchial_internal_indices.append(index_function())
# Compute the external indices for K-Means Clustering Results
hierarchial_external_validation = external_indices.external_indices(main.target, main.hierarchial_results['labels'])
hierarchial_external_indices = []
for index in choosen_external_indices:
index_function = getattr(hierarchial_external_validation, external_indices_functions[index])
print("Computing External Indices (hierarchial Clustering): %s Index"%index)
hierarchial_external_indices.append(index_function())
results_file.write("\"{file_name}\",\"{bag_num}\",{sample_size},\"{algorithm}\",\"{parameters}\",{n_clusters},\"{cluster_distrn}\",".format(file_name=bag_name,bag_num=sampled_data[x]['bag_number'], sample_size=main.n_samples, algorithm='hierarchial', parameters=main.hierarchial_results['parameters'].__repr__(), n_clusters=main.hierarchial_results['n_clusters'], cluster_distrn=main.hierarchial_results['clusters'].__repr__()))
for index in hierarchial_internal_indices:
results_file.write("{},".format(index))
for index in hierarchial_external_indices:
results_file.write("{},".format(index))
#results_file.write('\n')
results_file.write('\n')
'''
# Print the KMeans Clustering results to a 'results.csv' in warehouse
results_file.write("\"{dataset}\",{timestamp_id},{n_samples},{n_features},{n_classes},\"{class_distrn}\",{nominal_features},".format(dataset=sampled_data[0]['dataset_name'], timestamp_id=metadata['timestamp'], n_samples=metadata['n_samples'], n_features=metadata['n_features'], n_classes=len(metadata['classes']), class_distrn=metadata['classes'].__repr__(), nominal_features="No" if all(value is None for value in metadata['column_categories'].values()) else "Yes"))
results_file.write("\"{file_name}\",\"{bag_num}\",{sample_size},\"{algorithm}\",\"{parameters}\",{n_clusters},\"{cluster_distrn}\",".format(file_name=bag_name,bag_num=sampled_data[x]['bag_number'], sample_size=main.n_samples, algorithm='hierarchial', parameters=main.hierarchial_results['parameters'].__repr__(), n_clusters=main.hierarchial_results['n_clusters'], cluster_distrn=main.hierarchial_results['clusters'].__repr__()))
for index in kmeans_internal_indices:
results_file.write("{},".format(index))
for index in kmeans_external_indices:
results_file.write("{},".format(index))
results_file.write('\n')
'''
cluster_result = {
"file_name":bag_name,
"bag_num":sampled_data[x]['bag_number'],
"sample_size":main.n_samples,
"algorithm":'hierarchial',
"parameters":main.hierarchial_results['parameters'].__repr__(),
"n_clusters":main.hierarchial_results['n_clusters'],
"cluster_distrn":main.hierarchial_results['clusters'].__repr__(),
"kmeans_internal_indices":hierarchial_internal_indices,
"kmeans_external_indices":hierarchial_external_indices
}
tot_cluster_result.append(cluster_result)
del main
os.chdir(curr_pwd)
return tot_cluster_result
def spectral_indices(sampled_data):
# name of folder which contains the dataset's (randomly sampled) bag and metadata files.
'''Parameters for hdbscan Cluster Analysis'''
# Method used to determine the number of clusters in data for hdbscan Clustering.
spectral_n_clusters = 'gap' # Use gap statistics to estimate the optimal number of clusters from data (default)
spectral_kargs = {} # Other Keyword arguments (other than 'n_clusters') to :func:`sklearn.cluster.hdbscan`
""" Code to perform cluster analysis and Validation
Note: Not to be modified by the user
"""
internal_indices_functions = {
'WGSS':'wgss_index',
'BGSS':'bgss_index',
'Ball-Hall':'ball_hall_index',
'Banfeld-Raftery':'banfeld_raftery_index',
'Det-Ratio':'det_ratio_index',
'Ksq-DetW':'ksq_detw_index',
'Log-Det-Ratio':'log_det_ratio_index',
'Log-SS-Ratio':'log_ss_ratio_index',
'Scott-Symons':'scott_symons_index',
'Trace-WiB':'trace_wib_index',
'Silhouette':'silhouette_score',
'Calinski-Harabasz':'calinski_harabaz_score',
'C':'c_index',
'Dunn':'dunn_index',
'Davies-Bouldin':'davies_bouldin_index',
'Ray-Turi':'ray_turi_index',
'Hartigan':'hartigan_index',
'PBM':'pbm_index',
'Score':'score_function'
}
# Note: Strictly don't modify (or reorder) the 'choosen_internal_indices' list (without corresponding changes to 'results.csv' in warehouse)
choosen_internal_indices = [
'WGSS',
'BGSS',
'Ball-Hall',
'Banfeld-Raftery',
'Calinski-Harabasz',
'Det-Ratio',
'Ksq-DetW',
'Log-Det-Ratio',
'Log-SS-Ratio',
#'Scott-Symons',
'Silhouette',
'Trace-WiB',
'C',
'Dunn',
'Davies-Bouldin',
'Ray-Turi',
'PBM',
'Score'
]
# TODO*: Check if Sklearn's Precision, Recall, ... which are for classification work for clustering as well (change cluster indices and observe change in precision)
external_indices_functions = {
'Entropy':'entropy',
'Purity':'purity',
'Precision':'precision_coefficient',
'Recall':'recall_coefficient',
'F':'f_measure',
'Weighted-F':'weighted_f_measure',
'Folkes-Mallows':'folkes_mallows_index',
'Rand':'rand_index',
'Adjusted-Rand':'adjusted_rand_index',
'Adjusted-Mutual-Info':'adjusted_mutual_info',
'Normalised-Mutual-Info':'normalized_mutual_info',
'Homegeneity':'homogeneity_score',
'Completeness':'completness_score',
'V-Measure':'v_measure_score',
'Jaccard':'jaccard_coeff',
'Hubert Γ̂':'hubert_T_index',
'Kulczynski':'kulczynski_index',
'McNemar':'mcnemar_index',
'Phi':'phi_index',
'Russel-Rao':'russel_rao_index',
'Rogers-Tanimoto':'rogers_tanimoto_index',
'Sokal-Sneath1':'sokal_sneath_index1',
'Sokal-Sneath2':'sokal_sneath_index2'
}
# Note: Strictly don't modify (or reorder) the 'choosen_external_indices' list (without corresponding changes to 'results.csv' in warehouse)
choosen_external_indices = [
'Entropy',
'Purity',
'Precision',
'Recall',
'F',
'Weighted-F',
'Folkes-Mallows',
'Rand',
'Adjusted-Rand',
'Adjusted-Mutual-Info',
'Normalised-Mutual-Info',
'Homegeneity',
'Completeness',
'V-Measure',
'Jaccard',
'Hubert Γ̂',
'Kulczynski',
'McNemar',
'Phi',
'Russel-Rao',
'Rogers-Tanimoto',
'Sokal-Sneath1',
'Sokal-Sneath2'
]
bag_name = sampled_data[0]['dataset_name'].split('.')[0]
curr_pwd = str(os.getcwd())
indices_pwd = curr_pwd + '/indices/'
os.chdir(indices_pwd)
file_name_indices = bag_name+"spectral_indices.csv"
# Open 'results.csv' file in warehouse and append all results to it.
results_file = open(file_name_indices, 'a')
n_bags = len(sampled_data)
# Preprocess the 'kmeans_n_clusters' argument to standard accepted forms
if isinstance(spectral_n_clusters, str) and spectral_n_clusters in ['gap', 'n_classes']:
spectral_n_clusters = [spectral_n_clusters] * n_bags
elif isinstance(spectral_n_clusters, int):
spectral_n_clusters = [spectral_n_clusters] * n_bags
elif isinstance(spectral_n_clusters, list):
if len(spectral_n_clusters)!=n_bags:
print("error: The length of 'spectral_n_clusters' list supplied doesn't match the count of the number of bags")
sys.exit(1)
for bag_n_cluster in spectral_n_clusters:
if isinstance(bag_n_cluster, int):
pass
elif isinstance(bag_n_cluster, 'str') and bag_n_cluster in ['gap','n_classes']:
pass
else:
print("error: invalid entry %s in list supplied as argument to parameter 'spectral_n_clusters'"%bag_n_cluster.__repr__())
sys.exit()
else:
print("error: invalid argument to parameter 'spectral_n_clusters'. Accepted arguments: {'gap', 'n_classes', <int>, <list of {int,'gap','n_classes'} of shape (n_bags,)> }")
tot_cluster_result =[]
for x in range(len(sampled_data)):
print("Processing '{file_name}'".format(file_name=bag_name+"_bag_"+str(sampled_data[x]['bag_number'])))
dataset = sampled_data[x]
data, target = dataset['data'], dataset['target']
# Load the data into an eda object :obj:`main`
main = eda.eda()
main.load_data(data, target)
# perform kmeans clustering on the data
main.perform_spectral_clustering(n_clusters=spectral_n_clusters[x], **spectral_kargs,n_jobs=-1)
# Compute the internal indices for spectral Clustering Results
spectral_internal_validation = internal_indices.internal_indices(main.data, main.spectral_results['labels'])
spectral_internal_indices = []
for index in choosen_internal_indices:
index_function = getattr(spectral_internal_validation, internal_indices_functions[index])
print("Computing Internal Indices (spectral Clustering): %s Index"%index)
spectral_internal_indices.append(index_function())
# Compute the external indices for spectral Clustering Results
spectral_external_validation = external_indices.external_indices(main.target, main.spectral_results['labels'])
spectral_external_indices = []
for index in choosen_external_indices:
index_function = getattr(spectral_external_validation, external_indices_functions[index])
print("Computing External Indices (spectral Clustering): %s Index"%index)
spectral_external_indices.append(index_function())
results_file.write("\"{file_name}\",\"{bag_num}\",{sample_size},\"{algorithm}\",\"{parameters}\",{n_clusters},\"{cluster_distrn}\",".format(file_name=bag_name,bag_num=sampled_data[x]['bag_number'], sample_size=main.n_samples, algorithm='spectral', parameters=main.spectral_results['parameters'].__repr__(), n_clusters=main.spectral_results['n_clusters'], cluster_distrn=main.spectral_results['clusters'].__repr__()))
for index in spectral_internal_indices:
results_file.write("{},".format(index))
for index in spectral_external_indices:
results_file.write("{},".format(index))
results_file.write('\n')
cluster_result = {
"file_name":bag_name,
"bag_num":sampled_data[x]['bag_number'],
"sample_size":main.n_samples,
"algorithm":'spectral',
"parameters":main.spectral_results['parameters'].__repr__(),
"n_clusters":main.spectral_results['n_clusters'],
"cluster_distrn":main.spectral_results['clusters'].__repr__(),
"kmeans_internal_indices":spectral_internal_indices,
"kmeans_external_indices":spectral_external_indices
}
tot_cluster_result.append(cluster_result)
del main
os.chdir(curr_pwd)
return tot_cluster_result
def hdbscan_indices(sampled_data):
# name of folder which contains the dataset's (randomly sampled) bag and metadata files.
'''Parameters for hdbscan Cluster Analysis'''
# Method used to determine the number of clusters in data for hdbscan Clustering.
hdbscan_kargs = {} # Other Keyword arguments (other than 'n_clusters') to :func:`sklearn.cluster.hdbscan`
""" Code to perform cluster analysis and Validation
Note: Not to be modified by the user
"""
internal_indices_functions = {
'WGSS':'wgss_index',
'BGSS':'bgss_index',
'Ball-Hall':'ball_hall_index',
'Banfeld-Raftery':'banfeld_raftery_index',
'Det-Ratio':'det_ratio_index',
'Ksq-DetW':'ksq_detw_index',
'Log-Det-Ratio':'log_det_ratio_index',
'Log-SS-Ratio':'log_ss_ratio_index',
'Scott-Symons':'scott_symons_index',
'Trace-WiB':'trace_wib_index',
'Silhouette':'silhouette_score',
'Calinski-Harabasz':'calinski_harabaz_score',
'C':'c_index',
'Dunn':'dunn_index',
'Davies-Bouldin':'davies_bouldin_index',
'Ray-Turi':'ray_turi_index',
'Hartigan':'hartigan_index',
'PBM':'pbm_index',
'Score':'score_function'
}
# Note: Strictly don't modify (or reorder) the 'choosen_internal_indices' list (without corresponding changes to 'results.csv' in warehouse)
choosen_internal_indices = [
'WGSS',
'BGSS',
'Ball-Hall',
'Banfeld-Raftery',
'Calinski-Harabasz',
'Det-Ratio',
'Ksq-DetW',
'Log-Det-Ratio',
'Log-SS-Ratio',
#'Scott-Symons',
'Silhouette',
'Trace-WiB',
'C',
'Dunn',
'Davies-Bouldin',
'Ray-Turi',
'PBM',
'Score'
]
# TODO*: Check if Sklearn's Precision, Recall, ... which are for classification work for clustering as well (change cluster indices and observe change in precision)
external_indices_functions = {
'Entropy':'entropy',
'Purity':'purity',
'Precision':'precision_coefficient',
'Recall':'recall_coefficient',
'F':'f_measure',
'Weighted-F':'weighted_f_measure',
'Folkes-Mallows':'folkes_mallows_index',
'Rand':'rand_index',
'Adjusted-Rand':'adjusted_rand_index',
'Adjusted-Mutual-Info':'adjusted_mutual_info',
'Normalised-Mutual-Info':'normalized_mutual_info',
'Homegeneity':'homogeneity_score',
'Completeness':'completness_score',
'V-Measure':'v_measure_score',
'Jaccard':'jaccard_coeff',
'Hubert Γ̂':'hubert_T_index',
'Kulczynski':'kulczynski_index',
'McNemar':'mcnemar_index',
'Phi':'phi_index',
'Russel-Rao':'russel_rao_index',
'Rogers-Tanimoto':'rogers_tanimoto_index',
'Sokal-Sneath1':'sokal_sneath_index1',
'Sokal-Sneath2':'sokal_sneath_index2'
}
# Note: Strictly don't modify (or reorder) the 'choosen_external_indices' list (without corresponding changes to 'results.csv' in warehouse)
choosen_external_indices = [
'Entropy',
'Purity',
'Precision',
'Recall',
'F',
'Weighted-F',
'Folkes-Mallows',
'Rand',
'Adjusted-Rand',
'Adjusted-Mutual-Info',
'Normalised-Mutual-Info',
'Homegeneity',
'Completeness',
'V-Measure',
'Jaccard',
'Hubert Γ̂',
'Kulczynski',
'McNemar',
'Phi',
'Russel-Rao',
'Rogers-Tanimoto',
'Sokal-Sneath1',
'Sokal-Sneath2'
]
bag_name = sampled_data[0]['dataset_name'].split('.')[0]
curr_pwd = str(os.getcwd())
indices_pwd = curr_pwd + '/indices/'
os.chdir(indices_pwd)
file_name_indices = bag_name+"hdbscan_indices.csv"
# Open 'results.csv' file in warehouse and append all results to it.
results_file = open(file_name_indices, 'a')
n_bags = len(sampled_data)
tot_cluster_result =[]
for x in range(len(sampled_data)):
print("Processing '{file_name}'".format(file_name=bag_name+"_bag_"+str(sampled_data[x]['bag_number'])))
dataset = sampled_data[x]
data, target = dataset['data'], dataset['target']
# Load the data into an eda object :obj:`main`
main = eda.eda()
main.load_data(data, target)
# perform hdbscan clustering on the data
main.perform_hdbscan(**hdbscan_kargs)
# Compute the internal indices for hdbscan Clustering Results
hdbscan_internal_validation = internal_indices.internal_indices(main.data, main.hdbscan_results['labels'])
hdbscan_internal_indices = []
for index in choosen_internal_indices:
index_function = getattr(hdbscan_internal_validation, internal_indices_functions[index])
print("Computing Internal Indices (hdbscan Clustering): %s Index"%index)
hdbscan_internal_indices.append(index_function())
# Compute the external indices for hdbscan Clustering Results
hdbscan_external_validation = external_indices.external_indices(main.target, main.hdbscan_results['labels'])
hdbscan_external_indices = []
for index in choosen_external_indices:
index_function = getattr(hdbscan_external_validation, external_indices_functions[index])
print("Computing External Indices (hdbscan Clustering): %s Index"%index)
hdbscan_external_indices.append(index_function())
results_file.write("\"{file_name}\",\"{bag_num}\",{sample_size},\"{algorithm}\",\"{parameters}\",{n_clusters},\"{cluster_distrn}\",".format(file_name=bag_name,bag_num=sampled_data[x]['bag_number'], sample_size=main.n_samples, algorithm='hdbscan', parameters=main.hdbscan_results['parameters'].__repr__(), n_clusters=main.hdbscan_results['n_clusters'], cluster_distrn=main.hdbscan_results['clusters'].__repr__()))
for index in hdbscan_internal_indices:
results_file.write("{},".format(index))
for index in hdbscan_external_indices:
results_file.write("{},".format(index))
results_file.write('\n')
cluster_result = {
"file_name":bag_name,
"bag_num":sampled_data[x]['bag_number'],
"sample_size":main.n_samples,
"algorithm":'hdbscan',
"parameters":main.hdbscan_results['parameters'].__repr__(),
"n_clusters":main.hdbscan_results['n_clusters'],
"cluster_distrn":main.hdbscan_results['clusters'].__repr__(),
"kmeans_internal_indices":hdbscan_internal_indices,
"kmeans_external_indices":hdbscan_external_indices
}
tot_cluster_result.append(cluster_result)
del main
os.chdir(curr_pwd)
return tot_cluster_result