-
Notifications
You must be signed in to change notification settings - Fork 0
/
clusterModule.py
1298 lines (1183 loc) · 55 KB
/
clusterModule.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
#
# Copyright (c) University of Luxembourg 2019-2020.
# Created by Hazem FAHMY, [email protected], SNT, 2019.
# Modified by Mojtaba Bagherzadeh, [email protected], University of Ottawa, 2019.
#
from HeatmapModule import doDistance, collectHeatmaps, calculate_pixel_distance
from imports import shutil, itemgetter, pd, np, time, torch, os, pdist, shc, metrics, sys, normalize, \
AgglomerativeClustering, imageio, math, KMeans, join, exists, isfile, cv2, tqdm, Variable, makedirs, basename
from sklearn.preprocessing import LabelEncoder
import matplotlib.pyplot as plt
#import IEE_V1.ieepredict
import dataSupplier as DS
#import hdbscan
#from scipy import optimize
#from scipy.signal import savgol_filter
#from scipy.interpolate import splprep, splev
#from scipy.interpolate import UnivariateSpline
from kneed import KneeLocator
def run(caseFile):
layers = caseFile["layers"]
outputPath = caseFile["filesPath"]
mode = caseFile["clustMode"]
maxCluster = caseFile["maxCluster"]
start = time.time()
print("Start Clustering Operation")
minAvgICD = [0] * len(layers)
minAvgWICD = [0] * len(layers)
minAvgS = [0] * len(layers)
minAvgD = [0] * len(layers)
clsData = {}
i = 0
layersX = list()
outputPathX = join(outputPath, "ClusterAnalysis_" + str(mode))
if isfile(join(outputPath, "Layer9HMDistance.xlsx")):
if not exists(outputPathX):
os.mkdir(outputPathX)
for layerX in layers:
clsPath = join(outputPath, "ClusterAnalysis_" + str(mode), layerX + ".pt")
if not isfile(clsPath):
layersX.append(layerX)
print("Loading heatmaps' distance matrix \n")
heatMapDistanceExecl = pd.read_excel(join(outputPath, str(layerX) + "HMDistance.xlsx"))
print("Loaded \n")
heatMapDistanceExecl.drop(
heatMapDistanceExecl.columns[heatMapDistanceExecl.columns.str.contains('unnamed', case=False)],
axis=1, inplace=True)
print("clustering based on Layer " + str(layerX))
# maxCluster = int(len(heatMapDistanceExecl)/2)
clsData, minAvgICD[i], minAvgWICD[i] = doClustering(mode, heatMapDistanceExecl, outputPathX, str(layerX)
+ ".xlsx", maxCluster, layerX, "KG")
minAvgICD[0] = 1e9
minAvgWICD[0] = 1e9
torch.save(clsData, join(outputPathX, str(layerX) + ".pt"))
sys.stderr.write("Cluster of " + str(layerX) + " saved \n")
minAvgCluster = pd.DataFrame.from_dict(data=clsData, orient='index')
writer = pd.ExcelWriter(join(outputPathX, str(layerX) + ".xlsx"), engine='xlsxwriter')
minAvgCluster.to_excel(writer, sheet_name="ClustersSummary")
minAvgCluster = pd.DataFrame.from_dict(data=clsData['clusters'], orient='index')
minAvgCluster.to_excel(writer, sheet_name="ClustersDetails")
writer.close()
sys.stderr.write("Cluster of all layers saved \n")
end = time.time()
print("Total time consumption of operation Clustering is " + str((end - start) / 60.0) + " minutes.")
return caseFile
def exportImages_2P(clsData, clsData2, outPathX, caseFile, concepts, layerX):
imgsPath = []
for clusterID2 in clsData2['clusters']:
if len(clsData2['clusters'][clusterID2]['members']) == 1:
continue
clusterPath = join(outPathX, str(clusterID2))
#print("Exists")
DS.cleanMake(clusterPath, True)
clusterImages = []
clusterImages2 = []
clusterImages2List = []
for clusterID in clsData2['clusters'][clusterID2]['members']:
for img in clsData['clusters'][clusterID]['members']:
if concepts:
fileName = img.split(".")[0] + caseFile["imgExt"]
srcPath = join(caseFile["DataSetsPath"], str(caseFile["faceSubset"]) + "_Concepts", str(layerX), fileName)
dirPath = join(clusterPath, fileName)
if caseFile["datasetName"] == "HPD":
#origFile = join(caseFile["DataSetsPath"], "TestSet_Backup", str(int(img.split("_")[1])-1) + caseFile["imgExt"])
origFile = str(join(caseFile["DataSetsPath"], "TestSet_Backup_M", str((img.split("_")[1])) + caseFile["imgExt"])) #HPD-M
else:
origFile = join(caseFile["DataSetsPath"], "TestSet_Backup", str(img.split("_")[1]) + caseFile["imgExt"])
if origFile not in clusterImages2List:
clusterImages2.append(imageio.imread(origFile))
clusterImages2List.append(origFile)
else:
fileName = img.split("_")[1] + caseFile["imgExt"]
fileClass = img.split("_")[2]
fileSource = img.split("_")[0]
if fileSource == "Train":
srcPath = join(caseFile["trainDataPath"], fileClass, fileName)
elif fileSource == "Test":
srcPath = join(caseFile["testDataPath"], fileClass, fileName)
else:
srcPath = join(caseFile["improveDataPath"], fileClass, fileName)
dirPath = join(clusterPath, img + caseFile["imgExt"])
shutil.copy(srcPath, dirPath)
clusterImages.append(imageio.imread(srcPath))
imgsPath.append(join(outPathX, str(clusterID2) + '_' + str(len(clusterImages)) + '.gif'))
imageio.mimsave(join(outPathX, str(clusterID2) + '_' + str(len(clusterImages)) + '.gif'),
clusterImages)
if concepts:
if (len(clusterImages) / len(clusterImages2List)) > 1.5:
gifPath = join(outPathX, str(clusterID2) + '_' + str(len(clusterImages2List)) + 'imgsR.gif')
else:
gifPath = join(outPathX, str(clusterID2) + '_' + str(len(clusterImages2List)) + 'imgs.gif')
imgsPath.append(gifPath)
imageio.mimsave(gifPath, clusterImages2)
return imgsPath
def getCentroidDists(singleClusters, outputPathX, outputPathY, fileName):
if not exists(join(outputPathX, fileName)):
centroidDists = pd.DataFrame()
for clusterID in singleClusters:
diffList = []
centroidHMpath = join(outputPathY, str(clusterID), "centroidHM.pt")
if not exists(centroidHMpath):
continue
hm1 = (torch.load(centroidHMpath)).detach().cpu().numpy()
for clusterID2 in singleClusters:
centroidHMpath2 = join(outputPathY, str(clusterID2), "centroidHM.pt")
if not exists(centroidHMpath2):
continue
hm2 = (torch.load(centroidHMpath2)).detach().cpu().numpy()
diffList.append(math.sqrt(np.sum(np.power(np.subtract(hm1, hm2), 2))))
centroidDists[clusterID] = diffList
if not exists(outputPathX):
makedirs(outputPathX)
writer = pd.ExcelWriter(join(outputPathX, fileName), engine='xlsxwriter')
writer.book.use_zip64()
centroidDists.to_excel(writer)
writer.close()
centroidDists = pd.read_excel(join(outputPathX, fileName))
centroidDists.drop(centroidDists.columns[centroidDists.columns.str.contains('unnamed', case=False, na=False)],
axis=1,
inplace=True)
return centroidDists
def doPass2(outputPathX, layerX, centroidDists):
if not exists(join(outputPathX, str(layerX) + ".pt")):
clsData, _, _ = doClustering("AVG", centroidDists, outputPathX, str(layerX) + ".xlsx", 150, layerX, "R")
else:
clsData = torch.load(join(outputPathX, str(layerX) + ".pt"))
singleClusters = []
for clusterID in clsData['clusters']:
if len(clsData['clusters'][clusterID]['members']) == 1:
singleClusters.append(clsData['clusters'][clusterID]['members'][0])
continue
return clsData, singleClusters
def saveCentroidHMs(caseFile, concepts, outputPathY, layerX, outPath, clsData):
for clusterID in clsData['clusters']:
if len(clsData['clusters'][clusterID]['members']) == 1:
continue
clusterImages = []
clusterImages2 = []
clusterImages2List = []
clusterPath = join(outputPathY, str(clusterID))
if exists(clusterPath):
continue
DS.cleanMake(clusterPath, True)
centroidHM = 0.0
n = 0
for img in clsData['clusters'][clusterID]['members']:
if concepts:
fileName = img.split(".")[0] + caseFile["imgExt"]
srcPath = join(caseFile["DataSetsPath"], caseFile["faceSubset"] + "_Concepts", str(layerX), fileName)
dirPath = join(clusterPath, fileName)
outDir = join(caseFile["outputPathOriginal"], str(caseFile["faceSubset"]), "ConceptsData")
outPathX = join(outDir, "ConceptsHM", str(layerX), img.split(".")[0] + ".pt")
if caseFile["datasetName"] == "HPD":
#origFile = join(caseFile["DataSetsPath"], "TestSet_Backup", str(int(img.split("_")[1])-1) + caseFile["imgExt"])
origFile = str(join(caseFile["DataSetsPath"], "TestSet_Backup_M", str((img.split("_")[1])) + caseFile["imgExt"])) #HPD-M
else:
origFile = join(caseFile["DataSetsPath"], "TestSet_Backup", str((img.split("_")[1])) + caseFile["imgExt"])
if origFile not in clusterImages2List:
clusterImages2.append(imageio.imread(origFile))
clusterImages2List.append(origFile)
else:
fileName = img.split("_")[1] + caseFile["imgExt"]
fileClass = img.split("_")[2]
fileSource = img.split("_")[0]
if fileSource == "Train":
srcPath = join(caseFile["trainDataPath"], fileClass, fileName)
elif fileSource == "Test":
srcPath = join(caseFile["testDataPath"], fileClass, fileName)
else:
srcPath = join(caseFile["improveDataPath"], fileClass, fileName)
dirPath = join(clusterPath, img + caseFile["imgExt"])
outPathX = join(outPath, "Heatmaps", str(layerX), img.split(".")[0] + ".pt")
shutil.copy(srcPath, dirPath)
clusterImages.append(imageio.imread(srcPath))
AN = torch.load(outPathX)
if n == 0:
centroidHM = torch.add(AN, 0)
else:
centroidHM = torch.add(centroidHM, AN)
n += 1
centroidHM = centroidHM / n
torch.save(centroidHM, join(clusterPath, "centroidHM.pt"))
imageio.mimsave(join(outputPathY, str(clusterID) + '_' + str(len(clusterImages)) + '.gif'), clusterImages)
if concepts:
if (len(clusterImages)/len(clusterImages2List)) > 1.5:
gifPath = join(outputPathY, str(clusterID) + '_' + str(len(clusterImages2List)) + 'imgsR.gif')
else:
gifPath = join(outputPathY, str(clusterID) + '_' + str(len(clusterImages2List)) + 'imgs.gif')
imageio.mimsave(gifPath, clusterImages2)
def twoPass(caseFile, layerX, concepts, HMDistFile, outPath):
outputPathY = join(outPath, "2P_FC")
outputPathZ = join(outPath, "2P_Final")
if not exists(outputPathZ):
makedirs(outputPathZ)
if not exists(join(outputPathY, str(layerX) + ".pt")):
HMDist1 = pd.read_excel(HMDistFile)
HMDist1.drop(HMDist1.columns[HMDist1.columns.str.contains('unnamed', case=False)], axis=1, inplace=True)
clsData, _, _ = doClustering("WICDWard", HMDist1, outputPathY, str(layerX) + ".xlsx", 150, layerX, "R")
else:
clsData = torch.load(join(outputPathY, str(layerX) + ".pt"))
saveCentroidHMs(caseFile, concepts, outputPathY, layerX, outPath, clsData)
centroidClusters = []
for clusterID in clsData['clusters']:
centroidClusters.append(clusterID)
singleClusters = centroidClusters
i = 1
clsDataList = []
newImgsPath = []
while len(singleClusters) > 1:
outputPathX = join(outPath, "2P_RCC", str(i))
centroidDists = getCentroidDists(singleClusters, outputPathX, outputPathY, "centroidDists.xlsx")
clsData2, singleClusters = doPass2(outputPathX, layerX, centroidDists)
clsDataList.append(clsData2)
imgsPath = exportImages_2P(clsData, clsData2, outputPathX, caseFile, concepts, layerX)
print("SingleClusters:", len(singleClusters))
for img in imgsPath:
fileName = str(i) + "_" + str(basename(img)).split("_")[0] + "_" + str(basename(img)).split("_")[1]
shutil.copy(img, join(outputPathZ, fileName))
newImgsPath.append(join(outputPathZ, fileName))
i += 1
break
return clsData2
def saveIEE_KPs(caseFile, dst, model):
def forward_hook(self, input, output):
# print("forward hook..")
self.X = input[0]
self.Y = output
def update(img, x_p, y_p, x_t=0, y_t=0, gt=False):
height, width = img.shape[0], img.shape[1]
for idx in [-1, 0, 1]:
px = max(min(x_p + idx, width - 1), 0)
if x_t > 0 and y_t > 0:
tx = max(min(x_t + idx, width - 1), 0)
for jdx in [-1, 0, 1]:
py = max(min(y_p + jdx, height - 1), 0)
if x_t > 0 and y_t > 0:
ty = max(min(y_t + jdx, height - 1), 0)
if width > py > 0 and height > px > 0:
if gt: #red
img[py, px, 0] = 0
img[py, px, 1] = 0
img[py, px, 2] = 255
else: #blue
img[py, px, 0] = 0
img[py, px, 1] = 255
img[py, px, 2] = 0
if x_t > 0 and y_t > 0:
if width > ty > 0 and height > tx > 0:
if gt: #red
img[ty, tx, 0] = 0
img[ty, tx, 1] = 0
img[ty, tx, 2] = 255
else: #blue
img[ty, tx, 0] = 255
img[ty, tx, 1] = 0
img[ty, tx, 2] = 0
return img
trainPredict = predict.IEEPredictor(caseFile["trainDataNpy"], caseFile["modelPath"], 0)
trainDataSet, mainCounter = trainPredict.load_data(caseFile["trainDataNpy"])
totalInputs = 0
testPredict = predict.IEEPredictor(caseFile["testDataNpy"], caseFile["modelPath"], 0)
testDataSet, _ = testPredict.load_data(caseFile["testDataNpy"])
for (inputs, cp_labels) in tqdm(testDataSet):
totalInputs += len(inputs)
labels = cp_labels["gm"]
labels_gt = cp_labels["kps"]
labels_msk = np.ones(labels_gt.numpy().shape)
labels_msk[labels_gt.numpy() <= 1e-5] = 0
if torch.cuda.is_available():
model = model.cuda()
inputs = Variable(inputs.cuda())
else:
inputs = Variable(inputs)
model.conv2d_1.register_forward_hook(forward_hook)
predictA = model(inputs.float())
predict_cpu = predictA.cpu()
predict_cpu = predict_cpu.detach().numpy()
predict_xy1 = DS.transfer_target(predict_cpu, n_points=DS.n_points)
predict_xy = np.multiply(predict_xy1, labels_msk)
inputs_cpu = inputs.cpu()
inputs_cpu = inputs_cpu.detach().numpy()
num_sample = inputs_cpu.shape[0]
for idx in range(num_sample):
img = inputs_cpu[idx] * 255.
img = img[0, :]
img = np.repeat(img[:, :, np.newaxis], 3, axis=2)
xy = predict_xy[idx]
lab_xy = labels_gt[idx]
diff = np.square(np.array(lab_xy) - np.array(xy))
sum_diff = np.sqrt(diff[:,0] + diff[:,1])
rightbrow = [2, 3]
leftbrow = [0, 1]
mouth = [23, 24, 25, 26]
righteye = [16, 17, 18, 19, 20, 21, 22]
lefteye = [9, 10, 11, 12, 13, 14, 15]
noseridge = [4, 5]
nose = [6, 7, 8]
KParray = [0, 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]
area = caseFile["faceSubset"]
if area == "rightbrow":
KParray = rightbrow
elif area == "leftbrow":
KParray = leftbrow
elif area == "righteye":
KParray = righteye
elif area == "lefteye":
KParray = lefteye
elif area == "nose":
KParray = nose
elif area == "noseridge":
KParray = noseridge
elif area == "mouth":
KParray = mouth
label = 0
worst_label = 0
worst_KP = 0
for KP in sum_diff:
if KParray.count(label) > 0:
if KP > worst_KP:
worst_KP = KP
worst_label = label
label += 1
for coidx in KParray:
x_p = int(xy[coidx, 0] + 0.5)
y_p = int(xy[coidx, 1] + 0.5)
x_t = int(lab_xy[coidx][0] + 0.5)
y_t = int(lab_xy[coidx][1] + 0.5)
if coidx == worst_label:
img = update(img, x_p, y_p, x_t, y_t, True)
else:
img = update(img, x_p, y_p, x_t, y_t)
file_name = join(dst, str(mainCounter)+".png")
mainCounter += 1
if not exists(dst):
os.makedirs(dst)
if not isfile(file_name):
cv2.imwrite(file_name, img)
def drawClusters(caseFile, dst, model):
datasetName = caseFile["datasetName"]
layers = caseFile["layers"]
mode = caseFile["clustMode"]
DataSetsPath = caseFile["DataSetsPath"]
imgExt = caseFile["imgExt"]
outputPath = join(caseFile["filesPath"], "ClusterAnalysis_" + str(mode))
#if datasetName == "IEEKP":
#if drawKP:
#saveIEE_KPs(caseFile, dst, model)
for layerX in layers:
if torch.cuda.is_available():
clsData = torch.load(join(outputPath, str(layerX)) + ".pt")
else:
clsData = torch.load(join(outputPath, str(layerX)) + ".pt", map_location = torch.device('cpu'))
layerPath = join(outputPath, str(layerX))
if not exists(layerPath):
os.mkdir(layerPath)
else:
shutil.rmtree(layerPath)
os.mkdir(layerPath)
allImagesPath = join(layerPath, "AllClusters")
if not exists(allImagesPath):
os.mkdir(allImagesPath)
else:
shutil.rmtree(allImagesPath)
os.mkdir(allImagesPath)
for clusterID in clsData['clusters']:
clusterImages = []
clusterCounter = 0
clusterPath = join(layerPath, str(clusterID))
if not exists(clusterPath):
os.mkdir(clusterPath)
for img in clsData['clusters'][clusterID]['members']:
clusterCounter += 1
fileSource = img.split("_")[0]
if datasetName == "FLD":
fileName = img.split("_")[1] + imgExt
shutil.copy(join(dst, fileName), join(clusterPath, fileName))
else:
fileName = img.split("_")[1] + imgExt
fileClass = img.split("_")[2]
if fileSource == "Train":
shutil.copy(join(DataSetsPath, "TrainingSet", fileClass, fileName)
, join(clusterPath, fileName))
elif fileSource == "Test":
shutil.copy(join(DataSetsPath, "TestSet", fileClass, fileName),
join(clusterPath, fileName))
else:
shutil.copy(join(DataSetsPath, "ImprovementSet", "ImprovementSet", fileClass, fileName),
join(clusterPath, fileName))
if len(clsData['clusters'][clusterID]['members'])>1:
if len(clusterImages) < 140:
clusterImages.append(imageio.imread(join(clusterPath, fileName)))
clusterImages.append(imageio.imread(join(clusterPath, fileName)))
clusterImages.append(imageio.imread(join(clusterPath, fileName)))
if len(clusterImages)>3:
imageio.mimsave(join(allImagesPath, 'Cluster' + str(clusterID) + '_' + str(clusterCounter) + '.gif'),
clusterImages)
print("Exported " + str(layerX))
def plotFig(x_axis, y_axis, y_axis2, x_label, y_label, outputPath, layer, pointOne, pointTwo):
plt.plot(x_axis, y_axis)
if y_axis2 is not None:
plt.plot(x_axis, y_axis2)
if pointOne is not None:
plt.plot(x_axis[pointOne], y_axis[pointOne], 'ro', ms=5)
if pointTwo is not None:
if y_axis2 is not None:
plt.plot(x_axis[pointTwo], y_axis2[pointTwo], 'go', ms=5)
else:
plt.plot(x_axis[pointTwo], y_axis[pointTwo], 'go', ms=5)
plt.ylabel(y_label)
plt.xlabel(x_label)
plt.savefig(join(outputPath, layer + "_" + y_label + ".png"))
plt.cla()
plt.clf()
def KCluster(data, NumClusters):
print("Kmeans Clustering")
data_scaled = normalize(data, norm='max')
print("Distances are normalized")
kmeans = KMeans(n_clusters=NumClusters, random_state=0).fit(data_scaled)
label_array = kmeans.labels_
for i in range(0, len(label_array)):
label_array[i] = label_array[i] + 1
return label_array
def HACluster(data, maxCluster, library, linkage, metric, outputPath, layer, selection):
print("Hirearchial Agglomerative Clustering")
data_scaled = normalize(data, norm='max')
print("Distances are normalized")
#data_scaled = normalize(data)
if library is None:
if linkage == "Ward":
Z = shc.linkage(pdist(data_scaled), metric='euclidean', optimal_ordering=True, method="ward")
elif linkage == "Avg":
Z = shc.linkage(pdist(data_scaled), metric='euclidean', optimal_ordering=True, method="average")
elif linkage == "Complete":
Z = shc.linkage(pdist(data_scaled), metric='euclidean', optimal_ordering=True, method="complete")
elif linkage == "Single":
Z = shc.linkage(pdist(data_scaled), metric='euclidean', optimal_ordering=True, method="single")
elif linkage == "Centroid":
Z = shc.linkage(pdist(data_scaled), metric='euclidean', optimal_ordering=True, method="centroid")
elif linkage == "Median":
Z = shc.linkage(pdist(data_scaled), metric='euclidean', optimal_ordering=True, method="median")
elif linkage == "Weighted":
Z = shc.linkage(pdist(data_scaled), metric='euclidean', optimal_ordering=True, method="weighted")
print("Linkage", linkage, "data is computed")
start = 2
end = maxCluster + 1
cc_array = [0] * (end - start)
label_array = [0] * (end - start)
x_axis = list()
x_axis2 = list()
y_axis = list()
for i in range(start, end):
print("Clustering:", str(int(100.00*(i/(end-start))))+"%", end="\r")
labels = shc.fcluster(Z, t=i, criterion='maxclust')
#labels = (hdbscan.HDBSCAN(min_cluster_size=10)).fit_predict(data_scaled)
if metric == "Dunn":
aa = dunn(labels, data_scaled, "farthest", "nearest")
identifier = 'max'
if metric == "DunnICD":
aa = dunnICD(data_scaled, labels)
identifier = 'max'
if metric == "ICD":
aa = getAvgLayer_ICD(data_scaled, labels)
identifier = 'min'
if metric == "WICD":
aa = getAvgLayer_WICD(data_scaled, labels)
identifier = 'min'
if metric == "S":
aa = metrics.silhouette_score(data_scaled, labels, metric='euclidean')
identifier = 'max'
if metric == "DBI":
aa = metrics.davies_bouldin_score(data_scaled, labels)
identifier = 'min'
if metric == "AVG":
aa = getAVG(data_scaled, labels)
identifier = 'max'
clustCount = 0
for x in range(1, i + 1):
if ((list(labels)).count(x) > 1):
clustCount += 1
x_axis2.append(clustCount)
x_axis.append(i)
y_axis.append(aa)
cc_array[i - start] = aa
label_array[i - start] = labels
if identifier == 'min':
c = min(cc_array)
elif identifier == 'max':
c = max(cc_array)
index = [i for i, j in enumerate(cc_array) if j == c]
index = index[0]
aa = cc_array[index]
clusters = index + start
print("Clustering is done with " + str(metric) + ": " + str(aa) + " and " + str(clusters) + " clusters \n")
lenX = len(x_axis)
if lenX % 2 <= 0:
lenX = lenX - 1
#smoothY = savgol_filter(y_axis, lenX, 3)
if len(y_axis) == 1:
plotFig(x_axis, y_axis, None, "# Clusters", metric, outputPath, layer, None, None)
#plotFig(x_axis, None, None, "# Clusters", "GradientOfRaw", outputPath, layer, None, None)
return label_array[0]
gradient = gradientO4(np.array(y_axis), 4)
#gradientFit = savgol_filter(gradient, lenX, 3)
if selection == "KR":
kn_raw = KneeLocator(x_axis, y_axis, curve='convex', direction='decreasing')
kneeRaw = kn_raw.knee-start
plotFig(x_axis, y_axis, None, "# Clusters", metric, outputPath, layer, kneeRaw, None)
return label_array[kneeRaw]
elif selection == "KG":
kn_gradient = KneeLocator(x_axis, gradient, curve='concave', direction='increasing')
kneeGrad = kn_gradient.knee-start
plotFig(x_axis, gradient, None, "# Clusters", "GradientOfRaw", outputPath, layer, kneeGrad, None)
return label_array[kneeGrad]
elif selection == "R":
return label_array[index]
def HACluster_SklearnAvg(data: np.array, maxCluster=100): # data is a obseravation matrix of pair distances
data_scaled = normalize(data)
cc_array = [0] * maxCluster
for i in range(2, maxCluster):
cluster = AgglomerativeClustering(n_clusters=i, affinity='precomputed', linkage='average').fit(data_scaled)
# cluster = AgglomerativeClustering(n_clusters=i, affinity='euclidean', linkage='ward').fit(data_scaled)
cc = cluster.fit_predict(data_scaled)
aa = metrics.silhouette_score(data_scaled, cc, metric='euclidean')
cc_array[i - 2] = aa
c = max(cc_array)
index = [i for i, j in enumerate(cc_array) if j == c]
index = index[0]
aa = cc_array[index]
clusters = index + 2
cluster = AgglomerativeClustering(n_clusters=clusters, affinity='precomputed', linkage='average').fit(data_scaled)
# cluster = AgglomerativeClustering(n_clusters=clusters, affinity='euclidean', linkage='ward').fit(data_scaled)
cc = cluster.fit_predict(data_scaled)
clusterNumber = max(cc) + 1
aa = metrics.silhouette_score(data_scaled, cc, metric='euclidean')
print("Clustering is done with silhouette - Sklearn " + str(aa) + " and " + str(clusterNumber) + " clusters \n")
print(aa)
for i in range(0, len(cc)):
cc[i] = cc[i] + 1
return cc, aa
def HACluster_SklearnSingle(data: np.array, maxCluster=100): # data is a obseravation matrix of pair distances
data_scaled = normalize(data)
cc_array = [0] * maxCluster
for i in range(2, maxCluster):
cluster = AgglomerativeClustering(n_clusters=i, affinity='precomputed', linkage='single').fit(data_scaled)
# cluster = AgglomerativeClustering(n_clusters=i, affinity='euclidean', linkage='ward').fit(data_scaled)
cc = cluster.fit_predict(data_scaled)
aa = metrics.silhouette_score(data_scaled, cc, metric='euclidean')
cc_array[i - 2] = aa
c = max(cc_array)
index = [i for i, j in enumerate(cc_array) if j == c]
index = index[0]
aa = cc_array[index]
clusters = index + 2
cluster = AgglomerativeClustering(n_clusters=clusters, affinity='precomputed', linkage='single').fit(data_scaled)
# cluster = AgglomerativeClustering(n_clusters=clusters, affinity='euclidean', linkage='ward').fit(data_scaled)
cc = cluster.fit_predict(data_scaled)
clusterNumber = max(cc) + 1
aa = metrics.silhouette_score(data_scaled, cc, metric='euclidean')
print("Clustering is done with silhouette - Sklearn " + str(aa) + " and " + str(clusterNumber) + " clusters \n")
print(aa)
for i in range(0, len(cc)):
cc[i] = cc[i] + 1
return cc, aa
def HACluster_SklearnComplete(data: np.array, maxCluster=100): # data is a obseravation matrix of pair distances
data_scaled = normalize(data)
cc_array = [0] * maxCluster
for i in range(2, maxCluster):
cluster = AgglomerativeClustering(n_clusters=i, affinity='precomputed', linkage='complete').fit(data_scaled)
# cluster = AgglomerativeClustering(n_clusters=i, affinity='euclidean', linkage='ward').fit(data_scaled)
cc = cluster.fit_predict(data_scaled)
aa = metrics.silhouette_score(data_scaled, cc, metric='euclidean')
cc_array[i - 2] = aa
c = max(cc_array)
index = [i for i, j in enumerate(cc_array) if j == c]
index = index[0]
aa = cc_array[index]
clusters = index + 2
cluster = AgglomerativeClustering(n_clusters=clusters, affinity='precomputed', linkage='complete').fit(data_scaled)
# cluster = AgglomerativeClustering(n_clusters=clusters, affinity='euclidean', linkage='ward').fit(data_scaled)
cc = cluster.fit_predict(data_scaled)
clusterNumber = max(cc) + 1
aa = metrics.silhouette_score(data_scaled, cc, metric='euclidean')
print("Clustering is done with silhouette - Sklearn " + str(aa) + " and " + str(clusterNumber) + " clusters \n")
print(aa)
for i in range(0, len(cc)):
cc[i] = cc[i] + 1
return cc, aa
def getVarCluster(distance: np.array, clusterMember: list, clusterMembersName):
variance = 0
for m1 in range(0, len(clusterMember)):
for m2 in range(m1 + 1, len(clusterMember)):
indexM1 = clusterMembersName.get_loc(clusterMember[m1])
indexM2 = clusterMembersName.get_loc(clusterMember[m2])
variance += distance[indexM1][indexM2] ** 2
return variance
def getSumDistanceCluster(distance: np.array, clusterMember: list, clusterMembersName):
sumDistance = 0
for m1 in range(0, len(clusterMember)):
for m2 in range(m1 + 1, len(clusterMember)):
indexM1 = clusterMembersName.get_loc(clusterMember[m1])
indexM2 = clusterMembersName.get_loc(clusterMember[m2])
sumDistance += distance[indexM1][indexM2]
return sumDistance
def getVarClusterWithAddition(clusterMember: list, currentVar: int, newMember: str, heatMapTestSet,
heatmapTraningSet, metric):
variance = currentVar
for m1 in range(0, len(clusterMember)):
variance += doDistance(heatMapTestSet[m1], heatmapTraningSet[newMember], metric)
return variance
def dunnICD(distance, cc):
#return getAvgCluster_ICD(distance, cc)/getAvgLayer_ICD(distance, cc)
return getAvgCluster_ICD(distance, cc)/getFarthestLayer_ICD(distance, cc)
#return getAvgCluster_ICD(distance, cc)/getAvgLayer_WICD(distance, cc)
def getAvgCluster_ICD(distance: np.array, cc):
ClosestPairDists = list()
for label1 in range(1, max(cc)+ 1):
groupLen1 = list(cc).count(label1)
PairDists = list()
if groupLen1 > 1:
groupIndex1 = [0] * groupLen1
j = 0
for i in range(0, len(cc)):
if (cc[i] == label1):
groupIndex1[j] = i
j = j + 1
for label2 in range(1, max(cc)+1):
if label1 != label2:
groupLen2 = list(cc).count(label2)
if groupLen2 > 1:
groupIndex2 = [0] * groupLen2
j = 0
for i in range(0, len(cc)):
if (cc[i] == label2):
groupIndex2[j] = i
j = j + 1
for index in groupIndex1:
for index2 in groupIndex2:
PairDists.append(distance[index][index2])
if not len(PairDists) == 0:
ClosestPairDists.append(min(PairDists))
return sum(ClosestPairDists)/len(ClosestPairDists)
def getFarthestLayer_ICD(distance: np.array, cc):
Clusters_ICD = list()
for label in range(1, max(cc) + 1):
groupLen = list(cc).count(label)
# weight = groupLen / len(cc)
numPairs = int((groupLen * (groupLen - 1)) / 2)
Dists = [0] * numPairs
groupIndex = [0] * groupLen
j = 0
for i in range(0, len(cc)):
if (cc[i] == label):
groupIndex[j] = i
j = j + 1
k = 0
for index in groupIndex:
for index2 in groupIndex:
if (index2 > index):
Dists[k] = distance[index][index2]
k = k + 1
if (groupLen > 1):
Clusters_ICD.append(max(Dists))
return sum(Clusters_ICD)/len(Clusters_ICD)
def getAvgLayer_ICD(distance: np.array, cc):
Clusters_ICD = list()
for label in range(1, max(cc) + 1):
groupLen = list(cc).count(label)
# weight = groupLen / len(cc)
numPairs = int((groupLen * (groupLen - 1)) / 2)
Dists = [0] * numPairs
groupIndex = [0] * groupLen
j = 0
for i in range(0, len(cc)):
if (cc[i] == label):
groupIndex[j] = i
j = j + 1
k = 0
for index in groupIndex:
for index2 in groupIndex:
if (index2 > index):
Dists[k] = distance[index][index2]
k = k + 1
if (groupLen > 1):
Clusters_ICD.append(sum(Dists)/numPairs)
return sum(Clusters_ICD)/len(Clusters_ICD)
def getAVG(distance: np.array, cc):
Clusters_ICD = list()
Clusters_Indices = list()
for label in range(1, max(cc) + 1):
groupIndex = list()
for i in range(0, len(cc)):
if (cc[i] == label):
groupIndex.append(i)
Clusters_Indices.append(groupIndex)
k = 0
for cluster_indices1 in Clusters_Indices:
j = 0
for cluster_indices2 in Clusters_Indices:
if (j > k):
dist = list()
for index1 in cluster_indices1:
for index2 in cluster_indices2:
dist.append(distance[index1][index2])
Clusters_ICD.append(min(dist))
j += 1
k += 1
return sum(Clusters_ICD)/len(Clusters_ICD)
def getAvgLayer_NewICD(distance: np.array, cc):
n_clusters = 0
ICDlayer = 0
for label in range(1, max(cc) + 1):
groupLen = list(cc).count(label)
# weight = groupLen / len(cc)
numPairs = int((groupLen * (groupLen - 1)) / 2)
Dists = [0] * numPairs
groupIndex = [0] * groupLen
j = 0
for i in range(0, len(cc)):
if (cc[i] == label):
groupIndex[j] = i
j = j + 1
k = 0
for index in groupIndex:
for index2 in groupIndex:
if (index2 > index):
Dists[k] = distance[index][index2]
k = k + 1
if (groupLen > 1):
Avglabel = sum(Dists) / numPairs
ICDc = Avglabel * groupLen
# ICDc = Avglabel * weight
ICDlayer = ICDlayer + ICDc
n_clusters += 1
return ICDlayer / n_clusters
def getAvgLayer_WICD(distance: np.array, cc):
n_clusters = max(cc)
ICDlayer = 0
for label in range(1, n_clusters + 1):
groupLen = list(cc).count(label)
weight = groupLen / len(cc)
numPairs = int((groupLen * (groupLen - 1)) / 2)
Dists = [0] * numPairs
groupIndex = [0] * groupLen
j = 0
for i in range(0, len(cc)):
if (cc[i] == label):
groupIndex[j] = i
j = j + 1
k = 0
for index in groupIndex:
for index2 in groupIndex:
if (index2 > index):
Dists[k] = distance[index][index2]
k = k + 1
if (groupLen > 1):
Avglabel = sum(Dists) / numPairs
# ICDc = Avglabel
ICDc = Avglabel * weight
ICDlayer = ICDlayer + ICDc
return ICDlayer / n_clusters
def doClustering(mode, heatmapsDistance: dict, outPutPath: str, outputFile: str, maxCluster: int, layer, selection):
if not exists(outPutPath):
makedirs(outPutPath)
sys.stderr.write("Clustering ... \n")
clusters = {}
clusters['selected_ICD'] = False
clusters['selected_WICD'] = False
clusters['selected_S'] = False
clusters['selected_Dunn'] = False
if mode.startswith('AVG'):
metric = 'AVG'
linkage = 'Ward'
if mode.startswith('ICD'):
metric = 'ICD'
if mode == 'ICDWard':
linkage = 'Ward'
if mode == 'ICDAvg':
linkage = 'Avg'
if mode == 'ICDSingle':
linkage = 'Single'
if mode.startswith('WICD'):
metric = 'WICD'
if mode == 'WICDWard':
linkage = 'Ward'
if mode == 'WICDAvg':
linkage = 'Avg'
if mode.startswith('Dunn'):
metric = 'Dunn'
if mode == 'DunnWard':
linkage = 'Ward'
if mode == 'DunnAvg':
linkage = 'Avg'
if mode.startswith('DunnICD'):
metric = 'DunnICD'
if mode == 'DunnICDWard':
linkage = 'Ward'
if mode == 'DunnICDAvg':
linkage = 'Avg'
if mode.startswith('DBI'):
metric = 'DBI'
if mode == 'DBIWard':
linkage = 'Ward'
if mode == 'DBIAvg':
linkage = 'Avg'
if mode.startswith('S'):
metric = 'S'
if mode == 'SWard':
linkage = 'Ward'
if mode == 'SAvg':
linkage = 'Avg'
if mode.startswith('K'):
metric = 'K'
linkage = None
data = heatmapsDistance.values
print(metric)
print(linkage)
if metric == 'K':
cc = KCluster(data, maxCluster)
else:
cc = HACluster(data, maxCluster, None, linkage, metric, outPutPath, layer, selection)
data_scaled = normalize(data, norm='max')
numAC = 0
for label in range(1, max(cc) + 1):
if list(cc).count(label) > 1:
numAC += 1
if numAC == 0:
WICD = 1e9
ICD = 1e9
S = -1e9
DunnIndex = -1e9
DBI = 1e9
else:
WICD = getAvgLayer_WICD(data, cc)
ICD = getAvgLayer_ICD(data, cc)
S = metrics.silhouette_score(data_scaled, cc, metric='euclidean')
DunnIndex = dunn(cc, data_scaled, "farthest", "nearest")
DBI = metrics.davies_bouldin_score(data_scaled, cc)
clusters['WeightedavgLayer'] = WICD
clusters['avgLayer'] = ICD
# clusters['avgLayer'] = getAvgLayer_NewICD(heatmapsDistance.values, cc)
clusters['silhouette'] = S
clusters['dunn'] = DunnIndex
clusters['DBI'] = DBI
clusters['label list'] = cc
index = 0
for clusterID in cc:
if not 'clusters' in clusters:
clusters['clusters'] = {}
if not clusterID in clusters['clusters']:
clusters['clusters'][clusterID] = {}
if not 'members' in clusters['clusters'][clusterID]:
clusters['clusters'][clusterID]['members'] = []
clusters['clusters'][clusterID]['members'].append(heatmapsDistance.columns[index])
index = index + 1
avgDistLayers = []
nonSingleClusters = 0
for clusterID in clusters['clusters']:
clusters['clusters'][clusterID]['variance'] = getVarCluster(heatmapsDistance.values,
clusters['clusters'][clusterID][
'members'],
heatmapsDistance.columns)
clusters['clusters'][clusterID]['length'] = len(clusters['clusters'][clusterID]['members'])
if len(clusters['clusters'][clusterID]['members']) > 1:
nonSingleClusters += 1
clusters['clusters'][clusterID]['sumDistance'] = getSumDistanceCluster(
heatmapsDistance.values, clusters['clusters'][clusterID]['members'],
heatmapsDistance.columns)
clusters['clusters'][clusterID]['errorSum'] = clusters['clusters'][clusterID]['variance'] / \
clusters['clusters'][clusterID]['length']
avgDistLayers.append(
clusters['clusters'][clusterID]['sumDistance'] / clusters['clusters'][clusterID][
'length'])
print("Number of non-single clusters:", nonSingleClusters)
minAvgCluster = pd.DataFrame.from_dict(data=clusters, orient='index')
writer = pd.ExcelWriter(outPutPath + "/" + outputFile, engine='xlsxwriter')
minAvgCluster.to_excel(writer, sheet_name="ClustersSummary")
minAvgCluster = pd.DataFrame.from_dict(data=clusters['clusters'], orient='index')
minAvgCluster.to_excel(writer, sheet_name="ClustersDetails")
writer.close()
torch.save(clusters, outPutPath + "/" + outputFile.split(".")[0] + ".pt")
return clusters, ICD, WICD
def inter_cluster_distances(labels, distances, method='nearest'):
"""Calculates the distances between the two nearest points of each cluster.
:param labels: a list containing cluster labels for each of the n elements
:param distances: an n x n numpy.array containing the pairwise distances between elements
:param method: `nearest` for the distances between the two nearest points in each cluster, or `farthest`
"""
if method == 'nearest':
return __cluster_distances_by_points(labels, distances)
elif method == 'farthest':
return __cluster_distances_by_points(labels, distances, farthest=True)
def __cluster_distances_by_points(labels, distances, farthest=False):
n_unique_labels = len(np.unique(labels))
cluster_distances = np.full((n_unique_labels, n_unique_labels),
float('inf') if not farthest else 0)
np.fill_diagonal(cluster_distances, 0)
for i in np.arange(0, len(labels) - 1):
for ii in np.arange(i, len(labels)):
if labels[i] != labels[ii] and (
(not farthest and
distances[i, ii] < cluster_distances[labels[i], labels[ii]])
or
(farthest and
distances[i, ii] > cluster_distances[labels[i], labels[ii]])):
cluster_distances[labels[i], labels[ii]] = cluster_distances[
labels[ii], labels[i]] = distances[i, ii]
return cluster_distances
def diameter(labels, distances, method='farthest'):
"""Calculates cluster diameters
:param labels: a list containing cluster labels for each of the n elements
:param distances: an n x n numpy.array containing the pairwise distances between elements
:param method: either `mean_cluster` for the mean distance between all elements in each cluster, or `farthest` for the distance between the two points furthest from each other
"""
n_clusters = len(np.unique(labels))