-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathvisualize.py
1770 lines (1534 loc) · 86.9 KB
/
visualize.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
import torch
import os
from PIL import Image, ImageDraw
from facenet_pytorch import MTCNN, extract_face, InceptionResnetV1
import random
import torchvision.models as models
from torchvision.models.resnet import BasicBlock
import torch.optim as optim
from torchvision import transforms
from tvqa_dataset import TVQADataset, load_json, save_json, get_test_transforms
from train import VGGFacePlus, VGGFaceSubtitle, VGGSupervised
import json
from torch.utils.data import DataLoader
from pathlib import Path
from tqdm import tqdm
import xlsxwriter
import pandas as pd
import numpy as np
from sklearn.manifold import TSNE
from sklearn.cluster import AgglomerativeClustering, KMeans, MiniBatchKMeans
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib.patheffects as PathEffects
import openpyxl
from openpyxl_image_loader import SheetImageLoader
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
import math
import torch.nn.functional as F
import umap
import umap.plot
from matplotlib.colors import LinearSegmentedColormap
from sklearn.metrics import confusion_matrix, classification_report
import logging
import argparse
from simcse import SimCSE
from train import L2Norm
from config import default_argument_parser, get_cfg, set_global_cfg, global_cfg
from fvcore.common.file_io import PathManager
from sentence_transformers import SentenceTransformer
from matplotlib.patches import Ellipse
def weighted_purity(Y, C):
"""Computes weighted purity of HAC at one particular clustering "C".
Y, C: np.array([...]) containing unique cluster indices (need not be same!)
Note: purity --> 1 as the number of clusters increase, so don't look at this number alone!
"""
purity = 0.
uniq_clid, clustering_skew = np.unique(C, return_counts=True)
num_samples = np.zeros(uniq_clid.shape)
# loop over all predicted clusters in C, and measure each one's cardinality and purity
for k in uniq_clid:
# gt labels for samples in this cluster
k_gt = Y[np.where(C == k)[0]]
values, counts = np.unique(k_gt, return_counts=True)
# technically purity = max(counts) / sum(counts), but in WCP, the sum(counts) multiplies to "weight" the clusters
purity += max(counts)
purity /= Y.shape[0]
return purity, clustering_skew
def NMI(Y, C):
"""Normalized Mutual Information: Clustering performance between ground-truth Y and prediction C
Based on https://course.ccs.neu.edu/cs6140sp15/7_locality_cluster/Assignment-6/NMI.pdf
Result matches examples on pdf
Example:
Y = np.array([1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3])
C = np.array([1, 1, 1, 2, 2, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 2])
NMI(Y, C) = 0.1089
C = np.array([1, 1, 1, 2, 2, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2])
NMI(Y, C) = 0.2533
"""
def entropy(labels):
# H(Y) and H(C)
H = 0.
for k in np.unique(labels):
p = (labels == k).sum() / labels.size
H -= p * np.log2(p)
return H
def h_y_given_c(labels, pred):
# H(Y | C)
H = 0.
for c in np.unique(pred):
p_c = (pred == c).sum() / pred.size
labels_c = labels[pred == c]
for k in np.unique(labels_c):
p = (labels_c == k).sum() / labels_c.size
H -= p_c * p * np.log2(p)
return H
h_Y = entropy(Y)
h_C = entropy(C)
h_Y_C = h_y_given_c(Y, C)
# I(Y; C) = H(Y) - H(Y|C)
mi = h_Y - h_Y_C
# NMI = 2 * MI / (H(Y) + H(C))
nmi = 2 * mi / (h_Y + h_C)
return nmi
def to_1D(series):
return pd.Series([x.item() for _list in series for x in _list])
class SaveOutput:
"""
Utility function to visualize the outputs of PCA and t-SNE
"""
def __init__(self):
self.outputs = []
def __call__(self, module, module_in, module_out):
self.outputs.append(module_out)
def clear(self):
self.outputs = []
def get_children(model: torch.nn.Module):
# get children form model!
children = list(model.children())
flatt_children = []
if children == []:
# if model has no children; model is last child! :O
return model
else:
# look for children from children... to the last child!
for child in children:
try:
flatt_children.extend(get_children(child))
except TypeError:
flatt_children.append(get_children(child))
return flatt_children
def discrete_cmap(N, base_cmap=None):
"""Create an N-bin discrete colormap from the specified input map"""
# Note that if base_cmap is a string or None, you can simply do
# return plt.cm.get_cmap(base_cmap, N)
# The following works for string, None, or a colormap instance:
if base_cmap is None:
return plt.cm.get_cmap(base_cmap, N)
base = plt.cm.get_cmap(base_cmap)
color_list = base(np.linspace(0, 1, N))
cmap_name = base.name + str(N)
return LinearSegmentedColormap.from_list(cmap_name, color_list, N)
def make_excel(model, dataset, source, data_path, path_to_faces, file_name):
"""
make_excel(model=model, dataset=tvqa_all, source="dataloader",
# data_path="./dataset/frames_hq/friends_frames/",
# path_to_faces="./dataset/friends_frames/", file_name="new_all_data.xlsx")
make_excel(model=model, dataset=tvqa_test, source="dataloader", file_name="test_data.xlsx")
make_excel(model=model, dataset=tvqa_all, source="dataloader", file_name="all_data.xlsx")
:param model:
:param dataset:
:param source:
:param file_name:
:return:
"""
workbook = xlsxwriter.Workbook(f"./dataset/excel/{file_name}")
worksheet = workbook.add_worksheet()
if source == "dataloader":
data_loader = DataLoader(dataset, batch_size=1, shuffle=False, num_workers=0)
worksheet.write('A1', 'weak label')
worksheet.write('B1', 'correct label')
worksheet.write('C1', 'prediction')
worksheet.write('D1', 'week=correct')
worksheet.write('E1', 'predict=correct')
worksheet.write('F1', 'image')
worksheet.write('G1', 'face')
worksheet.write('H1', 'image_loc')
worksheet.write('I1', 'face_loc')
for iteration, data in tqdm(enumerate(data_loader)):
# predictions = model(data['image'])
ann = dataset.anns[str(iteration)]
# print(os.path.join(path_to_faces, ann["face"]))
img = Image.open(os.path.join(path_to_faces, ann["face"]))
draw = ImageDraw.Draw(img)
draw.text((0, 0), f'label: {ann["name"]}', (255, 255, 255))
# draw.text((0, 10), f'prediction: {dataset.id_to_lbs[int(predictions.argmax())]}', (255, 255, 255))
# img.save(os.path.join(vis_path, ann["face"]))
worksheet.write(f'A{iteration+2}', ann["name"]) #weak label
# worksheet.write(f'C{iteration+2}', dataset.id_to_lbs[int(predictions.argmax())]) #prediction
face = ann["face"]
worksheet.insert_image(f'F{iteration+2}', os.path.join(data_path, face[0:28]+f"/{face.split('_')[-2]}.jpg")) #image
# face: friends_s01e01_seg02_clip_03_00108_0.png
# tvqa_experiment/dataset/frames_hq/friends_frames/friends_s01e01_seg02_clip_03/00108.jpg
worksheet.insert_image(f'G{iteration + 2}', os.path.join(path_to_faces, ann["face"])) # face
worksheet.write(f'H{iteration + 2}', face[0:28]+f"/{face.split('_')[-2]}.jpg") # image_loc
worksheet.write(f'I{iteration + 2}', ann["face"]) # face_loc
workbook.close()
def make_excel_for_test(new_anns):
import xlsxwriter
data_path = "./dataset/frames_hq/friends_frames/"
path_to_faces = "./dataset/friends_frames/"
workbook = xlsxwriter.Workbook(f"./dataset/excel/s01e01_new_new.xlsx")
worksheet = workbook.add_worksheet()
worksheet.write('A1', 'weak label')
worksheet.write('B1', 'correct label')
worksheet.write('C1', 'prediction')
worksheet.write('D1', 'week=correct')
worksheet.write('E1', 'predict=correct')
worksheet.write('F1', 'image')
worksheet.write('G1', 'face')
worksheet.write('H1', 'image_loc')
worksheet.write('I1', 'face_loc')
old_anns = load_json("./dataset/all_annotations.json")
for iteration, ann in enumerate(new_anns.values()):
worksheet.write(f'A{iteration + 2}', "".join(ann["name"])) # weak label
face = ann["face"]
worksheet.insert_image(f'F{iteration + 2}',
os.path.join(data_path, face[0:28] + f"/{face.split('_')[-2]}.jpg"))
worksheet.insert_image(f'G{iteration + 2}', os.path.join(path_to_faces, ann["face"])) # face
worksheet.write(f'H{iteration + 2}', face[0:28] + f"/{face.split('_')[-2]}.jpg") # image_loc
worksheet.write(f'I{iteration + 2}', ann["face"]) # face_loc
for old_ann in old_anns.values():
if ann["face"] == old_ann["face"]:
worksheet.write(f'B{iteration + 2}', old_ann["target_name"]) # face_loc
workbook.close()
def visualize_embeddings(model, dataset, file_name, method="tsne", model_mode="facenet_pretrained", normalize=False, mode="nothing", preload=False):
"""
# visualize_embeddings(model=model, dataset=tvqa_all, file_name="all_data", method="tsne", model_mode=model_mode, normalize=False, mode="nothing", preload=True)
build_embeddings(model=model, dataset=tvqa_all, exp=exp, file_name="all_data", method="umap")
:param model: pretrained model that generates face embeddings
:param dataset: pointing to the data : tvqa_all, tvqa_train, tvqa_test, tvqa_val
:param file_name: excel file name -> all_data
:param method: tsne or umap
:param model_mode: facenet_pretrained or resnet_pretrained
:param normalize: whether to normalize embeddings or not
:param mode: pictures, text or nothing
:return: saves files of such visualizations
"""
dataset_loc = "./dataset/excel"
embeddings = calculate_embeddings(model, dataset, model_mode, normalize=normalize, preload=preload)
if method == "tsne":
# dists = [[(e1 - e2).norm().item() for e2 in embeddings] for e1 in embeddings]
# print(pd.DataFrame(dists)) #, columns=names, index=names??
print("TSNE is being calculated...")
tsne_grid = TSNE(random_state=10, n_iter=2000).fit_transform(embeddings.detach().numpy())
print("TSNE is calculated!")
df = pd.read_excel(f"{dataset_loc}/{file_name}.xls", usecols="A,B,C") # weak label, correct label, prediction
workbook = openpyxl.load_workbook(f"{dataset_loc}/{file_name}.xlsx")
sheet = workbook['Sheet1']
image_loader = SheetImageLoader(sheet)
hac8 = AgglomerativeClustering(n_clusters=8).fit_predict(embeddings.detach().numpy())
dataset.lbl_to_id['Unknown'] = 50
dataset.id_to_lbs[50] ='Unknown'
# hac8 = [dataset.id_to_lbs[predicted_lbl] for predicted_lbl in hac8]
fig, plt = visualize_tsne(tsne_grid, hac8, dataset.id_to_lbs, image_loader, mode=mode)
fig.savefig(os.path.join("", f"hac8_clusteringpredictions_{file_name}_{mode}pictures_{model_mode}.pdf"))
plt.clf()
correct_ids = [dataset.lbl_to_id[lbl] for lbl in df['correct label'][:-1].values.tolist()]
fig, plt = visualize_tsne(tsne_grid, correct_ids, dataset.id_to_lbs, image_loader, mode=mode)
fig.savefig(os.path.join("", f"tsne_corrects_{file_name}_{mode}pictures_{model_mode}.pdf"))
plt.clf()
prediction_ids = [dataset.lbl_to_id[lbl] for lbl in df['prediction'][:-1].values.tolist()]
fig, plt = visualize_tsne(tsne_grid, prediction_ids, dataset.id_to_lbs, image_loader, mode=mode)
fig.savefig(os.path.join("", f"tsne_predictions_{file_name}_{mode}pictures_{model_mode}.pdf"))
plt.clf()
elif method == "umap":
import matplotlib.pyplot as plt
df = pd.read_excel(f"{dataset_loc}/{file_name}.xls", usecols="A,B,C")
mapper = umap.UMAP().fit(embeddings.detach().numpy())
colors = df['correct label'][:-1]
targets = np.asarray([lbl for lbl in colors])
fig, ax = plt.subplots()
umap.plot.points(mapper, labels=targets, ax=ax)
fig.savefig(f"umap_{file_name}_{model_mode}.pdf")
def calculate_embeddings(model, dataset, emb_path, model_mode="facenet_pretrained", normalize=False, preload=False):
# emb_path = "./dataset/embeddings.pt"
if preload is True:
print("Preloading from existing embedding.pt file!")
return torch.load(emb_path)
print("Calculating the embeddings and saving them in embedding.pt file!")
# data_loader = DataLoader(dataset, batch_size=len(dataset), shuffle=False, num_workers=0) # todo batch size
data_loader = DataLoader(dataset, batch_size=4096, shuffle=False, num_workers=0)
flattened_model = get_children(model)
if model_mode == "resnet_pretrained" or model_mode == "facenet_reclassified":
save_output = SaveOutput()
hook_handles = []
for layer in flattened_model:
handle = layer.register_forward_hook(save_output)
hook_handles.append(handle)
with torch.no_grad():
for iteration, data in tqdm(enumerate(data_loader)):
model(data[0]['image'][None, :, :, :])
if model_mode == "resnet_pretrained":
temp_emb = save_output.outputs[len(save_output.outputs) - 2] # embeddings from the layer before logits
elif model_mode == "facenet_reclassified":
temp_emb = save_output.outputs[-1] # embeddings from the layer before loss layer
if iteration == 0:
embeddings = temp_emb
else:
embeddings = torch.cat((embeddings, temp_emb), 0)
save_output.clear()
elif model_mode == "facenet_pretrained":
with torch.no_grad():
for iteration, data in tqdm(enumerate(data_loader)):
if iteration == 0:
# embeddings = model(data[0]['image'][None, :, :, :])
embeddings = model(data['image'][:, :, :])
else:
# embeddings = torch.cat((embeddings, model(data[0]['image'][None, :, :, :])), 0)
embeddings = torch.cat((embeddings, model(data['image'][:, :, :])), 0)
if normalize:
embeddings = F.normalize(embeddings, p=2, dim=1)
torch.save(embeddings, emb_path)
return embeddings
def calculate_sentence_embeddings(dataset, emb_path, normalize=False, preload=False):
if preload is True:
print(f"Preloading from existing {emb_path} file!")
return torch.load(emb_path)
print("Calculating the embeddings and saving them in sentence_embedding.pt file!")
data_loader = DataLoader(dataset, batch_size=1, shuffle=False, num_workers=0, collate_fn=lambda x: x)
model = SentenceTransformer('sentence-transformers/paraphrase-mpnet-base-v2')
# model = SimCSE("princeton-nlp/sup-simcse-bert-base-uncased")
with torch.no_grad():
for iteration, data in tqdm(enumerate(data_loader)):
# weak_lbls = data[0]['name']
sub_emb = torch.from_numpy(model.encode(data[0]['subtitle'])[None, :])
# if weak_lbls:
# weak_lbls_embedding = model.encode(' '.join(weak_lbls))[None, :]
# else:
# weak_lbls_embedding = sub_emb
#
# sub_emb = torch.cat((sub_emb, weak_lbls_embedding), 1)
if iteration == 0:
all_embeddings = sub_emb
else:
all_embeddings = torch.cat((all_embeddings, sub_emb), 0)
if normalize:
all_embeddings = F.normalize(all_embeddings, p=2, dim=1)
torch.save(all_embeddings, emb_path)
return all_embeddings
def calculate_joint_embeddings(model, dataset, emb_path, model_mode="facenet_pretrained", normalize=False, preload=False):
# emb_path = "./dataset/embeddings.pt"
if preload is True:
print("Preloading from existing embedding.pt file!")
return torch.load(emb_path)
print("Calculating the embeddings and saving them in embedding.pt file!")
# data_loader = DataLoader(dataset, batch_size=len(dataset), shuffle=False, num_workers=0) # todo batch size
data_loader = DataLoader(dataset, batch_size=1, shuffle=False, num_workers=0, collate_fn=lambda x: x)
flattened_model = get_children(model)
save_output = SaveOutput()
hook_handles = []
for layer in flattened_model:
handle = layer.register_forward_hook(save_output)
hook_handles.append(handle)
with torch.no_grad():
for iteration, data in tqdm(enumerate(data_loader)):
model(data[0]['image'][None, :, :, :], None, data[0]['subtitle'], None)
temp_emb = save_output.outputs[-1] # embeddings from the layer before loss layer
if iteration == 0:
embeddings = temp_emb
else:
embeddings = torch.cat((embeddings, temp_emb), 0)
save_output.clear()
if normalize:
embeddings = F.normalize(embeddings, p=2, dim=1)
torch.save(embeddings, emb_path)
return embeddings
#todo: https://jakevdp.github.io/PythonDataScienceHandbook/05.12-gaussian-mixtures.html
def draw_ellipse(position, covariance, ax=None, **kwargs):
"""Draw an ellipse with a given position and covariance"""
# ax = ax or plt.gca()
# Convert covariance to principal axes
if covariance.shape == (2, 2):
U, s, Vt = np.linalg.svd(covariance)
angle = np.degrees(np.arctan2(U[1, 0], U[0, 0]))
width, height = 2 * np.sqrt(s)
else:
angle = 0
# width, height = 2 * np.sqrt(covariance)
width = 2 * np.sqrt(covariance)
height = width
# Draw the Ellipse
# for w, h in zip(width, height):
# ax.add_patch(Ellipse(position, w, h, angle, **kwargs))
for nsig in range(1, 4):
ax.add_patch(Ellipse(position, nsig * width, nsig * height, angle, **kwargs))
def plot_gmm(gmm, labels, tsne_grid, label=True):
fig = plt.figure(figsize=(8, 8))
ax = plt.subplot(aspect='equal')
# ax = ax or plt.gca()
# labels = gmm.fit(X).predict(X)
# if label:
# ax.scatter(tsne_grid[:, 0], tsne_grid[:, 1], c=labels, s=40, cmap='viridis', zorder=2)
# else:
# ax.scatter(tsne_grid[:, 0], tsne_grid[:, 1], s=40, zorder=2)
# ax.axis('equal')
w_factor = 0.2 / gmm.weights_.max()
for pos, covar, w in zip(gmm.means_, gmm.covariances_, gmm.weights_):
draw_ellipse(pos, covar, ax=ax, alpha=w * w_factor)
return fig, plt
def visualize_tsne(tsne_grid, label_ids, id_to_lbl, image_loader=None, mode="nothing"):
num_classes = len(id_to_lbl)
# convert to pandas
label_ids = pd.DataFrame(label_ids, columns=['label'])['label']
# create a scatter plot.
fig = plt.figure(figsize=(8, 8))
ax = plt.subplot(aspect='equal')
if not label_ids.isnull().values.any():
plt.scatter(tsne_grid[:, 0], tsne_grid[:, 1], lw=0, s=40, c=np.asarray(label_ids),
cmap=discrete_cmap(num_classes, "tab10"))
# , c = palette[np.asarray([lbl_to_id[lbl] for lbl in colors])]
# c = np.random.randint(num_classes, size=len(tsne_grid[:, 1]))
else:
plt.scatter(tsne_grid[:, 0], tsne_grid[:, 1], lw=0, s=40)
plt.xlim(-25, 25)
plt.ylim(-25, 25)
cbar = plt.colorbar(ticks=range(num_classes))
cbar.set_ticklabels(list(id_to_lbl.values()))
plt.clim(-0.5, num_classes - 0.5)
ax.axis('off')
ax.axis('tight')
if mode == "picture":
max_dim = 16
for i, (x, y) in enumerate(tsne_grid):
print(i, x, y)
tile = image_loader.get(f'G{i+2}')
rs = max(1, tile.width/max_dim, tile.height/max_dim)
tile = tile.resize((int(tile.width/rs), int(tile.height/rs)), Image.ANTIALIAS)
imagebox = OffsetImage(tile) #, zoom=0.2)
ab = AnnotationBbox(imagebox, (x, y), pad=0.1)
ax.add_artist(ab)
if mode == "text":
# add the labels for each digit corresponding to the label
if not label_ids.isnull().values.any():
txts = []
for id, lbl in id_to_lbl.items():
# Position of each label at median of data points.
xtext, ytext = np.median(tsne_grid[np.asarray(label_ids) == id, :], axis=0)
if math.isnan(xtext) or math.isnan(ytext): # this label does not exist in this set
continue
txt = ax.text(xtext, ytext, lbl, fontsize=10, zorder=100)
txt.set_path_effects([
PathEffects.Stroke(linewidth=2, foreground="w"),
PathEffects.Normal()])
txts.append(txt)
return fig, plt
def evaluate(model, dataset, model_mode):
data_loader = DataLoader(dataset, batch_size=1, shuffle=False, num_workers=0)
with torch.no_grad():
correct_target_names = []
correct_target_ids = []
target_ids = []
predictions = []
for data in tqdm(data_loader):
# target_ids.append(data['weak_label'])
correct_target_names.extend(data['correct_target_name'])
correct_target_ids.append(data['correct_target_id'])
if model_mode == "facenet_pretrained":
predictions = np.nan
continue
else:
prediction = model(data['image'])
predictions.append(int(prediction.argmax()))
# flatten list of lists
# target_ids = [item.item() for sublist in target_ids for item in sublist]
correct_target_ids = [item.item() for sublist in correct_target_ids for item in sublist]
results = pd.DataFrame({'correct_target_name': correct_target_names,
'correct_target_id': correct_target_ids,
'model_prediction': predictions,
# 'weak_label': target_ids,
# 'max_cluster_prediction': np.nan,
})
return results
def clustering_with_gmm(results, face_embeddings, tsne_grid, n_clusters=7):
from sklearn import mixture
# results["gmm"] = np.nan
model = mixture.GaussianMixture(n_components=n_clusters, covariance_type='spherical')
# a = model.fit(face_embeddings)
# labels = a.predict(face_embeddings)
labels = model.fit(tsne_grid).predict(tsne_grid)
results["gmm"] = labels
# probs = model.predict_proba(face_embeddings)
plt, fig = plot_gmm(model, labels, tsne_grid)
return results, plt, fig
def build_graph(embeddings, train_dataset, neighbours=3385, no_edge=True):
from sklearn.neighbors import kneighbors_graph
train_loader = DataLoader(train_dataset, batch_size=1, shuffle=False, num_workers=0)
knn_graph = kneighbors_graph(embeddings, neighbours, include_self=True) # make the full neighbour graph
knn_graph = knn_graph.toarray()
if no_edge:
images = []
with torch.no_grad():
for i, data in enumerate(train_loader):
img = '_'.join(data["face"][0].split("_")[:-1])
images.append(img)
for i1, img1 in enumerate(images):
for i2, img2 in enumerate(images):
if img1 == img2 and i1 != i2:
knn_graph[i1][i2] = 0.0
return knn_graph
def predict_with_clustering(results, embeddings, n_clusters, knn_graph=None, pred_mode="max_cluster_prediction"):
# from sklearn import mixture
# model = mixture.GaussianMixture(n_components=n_clusters, covariance_type='spherical')
# labels = model.fit(embeddings).predict(embeddings)
# results["gmm"] = labels
# results[pred_mode] = np.nan
embeddings = embeddings.detach().numpy() #.astype('float32')
# print(embeddings.dtype)
# logger.info(f"type of embeddings is {embeddings.dtype}")
if global_cfg.TRAINING.clustering == "AgglomerativeClustering":
hac8_id = AgglomerativeClustering(n_clusters=n_clusters).fit_predict(embeddings)
elif global_cfg.TRAINING.clustering == "KMeans":
hac8_id = KMeans(n_clusters=n_clusters).fit_predict(embeddings)
elif global_cfg.TRAINING.clustering == "MiniBatchKMeans":
hac8_id = MiniBatchKMeans(batch_size=global_cfg.TRAINING.kmeans_batch_size, n_clusters=n_clusters).fit_predict(embeddings)
# import pdb
# pdb.set_trace()
# if knn_graph is None:
# hac8_id = AgglomerativeClustering(n_clusters=n_clusters).fit_predict(embeddings)
# else:
# hac8_id = AgglomerativeClustering(n_clusters=n_clusters, connectivity=knn_graph).fit_predict(embeddings.detach().numpy())
hac8_id = pd.DataFrame(hac8_id, columns=['label'])
for i in range(n_clusters):
# true for all indices equal to that cluster
# if np.all(results.loc[hac8_id['label'] == 18, "weak_label_ids"]) == []: #todo: what have i done here??
# results.loc[hac8_id['label'] == i, pred_mode] = 0.6 #unknown
# else:
results.loc[hac8_id['label'] == i, pred_mode] = to_1D(results.loc[hac8_id['label'] == i, "weak_label_ids"]).value_counts().idxmax()
results[pred_mode] = pd.to_numeric(results[pred_mode], downcast='integer')
results['direct'] = results['weak_label_ids']
results['direct'] = results['direct'].apply(lambda x: x[0].item() if len(x) == 1 else np.nan)
results['M2'] = results[pred_mode]
results.loc[results['direct'].notnull(), 'M2'] = results.loc[results['direct'].notnull(), 'direct']
results['M2'] = pd.to_numeric(results['M2'], downcast='integer')
clustering_ids = hac8_id
return results, clustering_ids
def calc_accuracies(results, mode="max_cluster_prediction"):
correct = (results[mode] == results["correct_target_id"]).value_counts().loc[True]
incorrect = (results[mode] == results["correct_target_id"]).value_counts().loc[False]
accuracy = correct / (correct + incorrect)
# from sklearn.metrics import classification_report, accuracy_score
# or accuracy_score(results['correct_target_id'], results['max_cluster_prediction'])
return accuracy
def calc_accuracies_bbt(gt_id, predictions_id):
correct = np.count_nonzero(predictions_id == gt_id)
incorrect = len(predictions_id) - np.count_nonzero(predictions_id == gt_id)
accuracy = correct / (correct + incorrect)
# from sklearn.metrics import classification_report, accuracy_score
# or accuracy_score(results['correct_target_id'], results['max_cluster_prediction'])
return accuracy
def calc_per_class_prec_recall(results, mode="max_cluster_prediction"):
return classification_report(results['correct_target_id'], results[mode], digits=3)
def calc_per_class_prec_recall_bbt(train_dataset, gt_id, predictions_id):
return classification_report(gt_id, predictions_id, labels=list(train_dataset.lbl_to_id.keys()), digits=3)
def calc_per_class_accuracy(dataset, results, mode="max_cluster_prediction"):
cm = confusion_matrix(results['correct_target_id'], results[mode])
num_classes = len(dataset.lbl_to_id.keys())
plt.imshow(cm, cmap='plasma', interpolation='nearest')
plt.xticks(range(num_classes), np.array(list(dataset.lbl_to_id.keys())), rotation=90, fontsize=6)
plt.yticks(range(num_classes), np.array(list(dataset.lbl_to_id.keys())), rotation=0, fontsize=6)
# Plot a colorbar with label.
cb = plt.colorbar()
cb.set_label("Number of predictions")
# Add title and labels to plot.
plt.title("Confusion Matrix for predictions and correct labels")
plt.xlabel('Correct Label')
plt.ylabel('Predicted Label')
plt.savefig('confusion_matrix_upperbound.pdf')
plt.clf()
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
return cm.diagonal(), dataset.id_to_lbs
def calc_per_class_accuracy_bbt(dataset, gt_names, predictions_names):
cm = confusion_matrix(gt_names, predictions_names, labels=list(dataset.lbl_to_id.keys()))
num_classes = len(dataset.lbl_to_id.keys())
plt.imshow(cm, cmap='plasma', interpolation='nearest')
plt.xticks(range(num_classes), np.array(list(dataset.lbl_to_id.keys())), rotation=90, fontsize=6)
plt.yticks(range(num_classes), np.array(list(dataset.lbl_to_id.keys())), rotation=0, fontsize=6)
# Plot a colorbar with label.
cb = plt.colorbar()
cb.set_label("Number of predictions")
# Add title and labels to plot.
plt.title("Confusion Matrix for predictions and correct labels")
plt.xlabel('Correct Label')
plt.ylabel('Predicted Label')
plt.savefig('confusion_matrix_upperbound.pdf')
plt.clf()
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
return cm.diagonal(), dataset.id_to_lbs
def exp_num_clusters(cluster_range, results, embeddings, test_dataset):
accuracies_per_cluster = []
clusters = []
for n in cluster_range:
results, clustering_ids = predict_with_clustering(results, embeddings, n_clusters=n)
prediction_mode = "max_cluster_prediction"
print(
f"per sample accuracy is {calc_accuracies(results, mode=prediction_mode)}")
accuracies = calc_per_class_accuracy(test_dataset, results, mode=prediction_mode)
print(f"mean per class accuracy: {accuracies[0].mean()}")
print(f"per class accuracies: {accuracies}")
accuracies_per_cluster.append(accuracies[0].mean())
print(f"per class precision and recalls: {calc_per_class_prec_recall(results, mode=prediction_mode)}")
clusters.append(n)
fig = plt.figure(figsize=(8, 6))
ax = plt.subplot(aspect='equal')
# plt.style.use('seaborn-darkgrid')
# plt.yticks(np.arange(0.0, 1.1, 0.1))
ax.axis('tight')
plt.ylim(0.0, 1.0)
plt.xlim(6, 31)
plt.bar(x=clusters, height=accuracies_per_cluster, width=0.4, color='#c3abd0') # width
plt.plot(clusters, accuracies_per_cluster, color='#815f76')
plt.ylabel("Accuracy", rotation=90)
plt.xlabel("Number of Clusters")
fig.savefig(os.path.join(f"./output/ablation_num_clusters_friends/number_of_clusters_2.pdf"))
plt.clf()
def cleanse_labels(dataset, results, file_path):
anns = dataset.anns
for ann, max_prediction in zip(anns.values(), results['max_cluster_prediction']):
ann['cleansed'] = dataset.id_to_lbs[max_prediction]
save_json(anns, file_path=file_path)
def save_predictions(id_to_lbs, results, file_path, prediction_dict, prediction_mode='cleansed'):
for ann, max_prediction in zip(prediction_dict.values(), results[prediction_mode]):
ann[prediction_mode] = id_to_lbs[max_prediction]
save_json(prediction_dict, file_path=file_path)
return prediction_dict
def evaluate_self_supervised(train_dataset, test_dataset, face_embeddings, mode="baseline1"):
train_loader = DataLoader(train_dataset, batch_size=1, shuffle=False, num_workers=0)
test_loader = DataLoader(test_dataset, batch_size=1, shuffle=False, num_workers=0)
with torch.no_grad():
correct_target_names = []
correct_target_ids = []
weak_ids = []
cleansed_ids = []
face_emb = []
unknown_id = torch.tensor([train_dataset.lbl_to_id["Unknown"]])
for train_data, test_data, face_embedding in tqdm(zip(train_loader, test_loader, face_embeddings)):
if mode == "baseline0":
if train_data['weak_id']:
choice = random.choice(train_data['weak_id'])
weak_ids.append(choice if choice in list(train_dataset.id_to_lbs.keys()) else unknown_id)
else:
weak_ids.append(unknown_id)
elif mode == "baseline1":
weak_ids.append(train_data['weak_id'])
correct_target_names.extend(test_data['correct_target_name'])
correct_target_ids.append(test_data['correct_target_id'])
cleansed_ids.append(train_dataset.lbl_to_id[train_data['cleansed'][0]])
face_emb.append(face_embedding)
# flatten list of lists
# weak_ids = [item.item() for sublist in weak_ids for item in sublist]
correct_target_ids = [item.item() for sublist in correct_target_ids for item in sublist]
if mode == "baseline0":
results = pd.DataFrame({'correct_target_name': correct_target_names,
'correct_target_id': correct_target_ids,
'random_weak_label': weak_ids,
})
elif mode == "baseline1":
results = pd.DataFrame({'correct_target_name': correct_target_names,
'correct_target_id': correct_target_ids,
'weak_label_ids': weak_ids,
'max_cluster_prediction': np.nan,
'cleansed': cleansed_ids,
'subtitle_prediction': np.nan,
'face_embedding': face_emb,
'0': np.nan,
'1': np.nan,
'2': np.nan,
'3': np.nan,
'4': np.nan,
'5': np.nan,
'6': np.nan,
'min_distance': np.nan,
'closest_cluster': np.nan,
})
return results
def prepare_result(train_dataset, face_embeddings):
train_loader = DataLoader(train_dataset, batch_size=1, shuffle=False, num_workers=0)
with torch.no_grad():
weak_ids = []
cleansed_ids = []
face_emb = []
unknown_id = torch.tensor([train_dataset.lbl_to_id["Unknown"]])
for train_data, face_embedding in tqdm(zip(train_loader, face_embeddings)):
weak_ids.append(train_data['weak_id'])
cleansed_ids.append(train_dataset.lbl_to_id[train_data['cleansed'][0]])
face_emb.append(face_embedding)
# flatten list of lists
# correct_target_ids = [item.item() for sublist in correct_target_ids for item in sublist]
results = pd.DataFrame({'face_embedding': face_emb,
'weak_label_ids': weak_ids,
'correct_target_name': np.nan,
'correct_target_id': np.nan,
'max_cluster_prediction': np.nan,
'cleansed': cleansed_ids,
'0': np.nan,
'1': np.nan,
'2': np.nan,
'3': np.nan,
'4': np.nan,
'5': np.nan,
'6': np.nan,
'7': np.nan,
'8': np.nan,
'min_distance': np.nan,
'closest_cluster': np.nan,
})
return results
def evaluate_ep_1_5(train_dataset, face_embeddings, mode="baseline1"):
train_loader = DataLoader(train_dataset, batch_size=1, shuffle=False, num_workers=0)
# test_loader = DataLoader(test_dataset, batch_size=1, shuffle=False, num_workers=0)
with torch.no_grad():
correct_target_names = []
correct_target_ids = []
weak_ids = []
cleansed_ids = []
face_emb = []
unknown_id = torch.tensor([train_dataset.lbl_to_id["Unknown"]])
for train_data, face_embedding in tqdm(zip(train_loader, face_embeddings)):
if mode == "baseline0":
if train_data['weak_id']:
choice = random.choice(train_data['weak_id'])
weak_ids.append(choice if choice in list(train_dataset.id_to_lbs.keys()) else unknown_id)
else:
weak_ids.append(unknown_id)
elif mode == "baseline1":
weak_ids.append(train_data['weak_id'])
correct_target_names.extend(train_data['correct_target_name'])
correct_target_ids.append(train_data['correct_target_id'])
cleansed_ids.append(train_dataset.lbl_to_id[train_data['cleansed'][0]])
face_emb.append(face_embedding)
# flatten list of lists
# weak_ids = [item.item() for sublist in weak_ids for item in sublist]
correct_target_ids = [item.item() for sublist in correct_target_ids for item in sublist]
if mode == "baseline0":
results = pd.DataFrame({'correct_target_name': correct_target_names,
'correct_target_id': correct_target_ids,
'random_weak_label': weak_ids,
})
elif mode == "baseline1":
results = pd.DataFrame({'correct_target_name': correct_target_names,
'correct_target_id': correct_target_ids,
'weak_label_ids': weak_ids,
'max_cluster_prediction': np.nan,
'cleansed': cleansed_ids,
'face_embedding': face_emb,
'0': np.nan,
'1': np.nan,
'2': np.nan,
'3': np.nan,
'4': np.nan,
'5': np.nan,
'6': np.nan,
'min_distance': np.nan,
'closest_cluster': np.nan,
})
return results
def evaluate_oracle_supervised(model, test_dataset, face_embeddings, mode="baseline1"):
# train_loader = DataLoader(train_dataset, batch_size=1, shuffle=False, num_workers=0)
test_loader = DataLoader(test_dataset, batch_size=1, shuffle=False, num_workers=0)
with torch.no_grad():
correct_target_names = []
correct_target_ids = []
weak_ids = []
cleansed_ids = []
face_emb = []
predictions = []
unknown_id = torch.tensor([test_dataset.lbl_to_id["Unknown"]])
for test_data, face_embedding in tqdm(zip(test_loader, face_embeddings)):
if mode == "baseline0":
if test_data['weak_label']:
choice = random.choice(test_data['weak_id'])
weak_ids.append(choice if choice in list(test_dataset.id_to_lbs.keys()) else unknown_id)
else:
weak_ids.append(unknown_id)
elif mode == "baseline1":
weak_ids.append(test_data['weak_id'])
correct_target_names.extend(test_data['correct_target_name'])
correct_target_ids.append(test_data['correct_target_id'])
cleansed_ids.append(test_dataset.lbl_to_id[test_data['cleansed'][0]])
face_emb.append(face_embedding)
prediction = model(test_data['image'])
predictions.append(int(prediction.argmax()))
# flatten list of lists
# weak_ids = [item.item() for sublist in weak_ids for item in sublist]
correct_target_ids = [item.item() for sublist in correct_target_ids for item in sublist]
if mode == "baseline0":
results = pd.DataFrame({'correct_target_name': correct_target_names,
'correct_target_id': correct_target_ids,
'random_weak_label': weak_ids,
})
elif mode == "baseline1":
results = pd.DataFrame({
'correct_target_name': correct_target_names,
'correct_target_id': correct_target_ids,
'weak_label_ids': weak_ids,
'max_cluster_prediction': np.nan,
'cleansed': cleansed_ids,
'face_embedding': face_emb,
'model_prediction': predictions,
'0': np.nan,
'1': np.nan,
'2': np.nan,
'3': np.nan,
'4': np.nan,
'5': np.nan,
'6': np.nan,
'min_distance': np.nan,
'closest_cluster': np.nan,
})
return results
def match_bbox(train_dataset, test_dataset):
matchings = {str(i): {"matching": [], "iou": []} for i in range(len(test_dataset))}
for i_test, s_test in tqdm(test_dataset.anns.items()):
for i_train, s_train in train_dataset.anns.items():
if s_test['clip'] + '_' + s_test['img'] == s_train['clip'] + '_' + s_train['img']:
iou = calc_iou(s_test['bbox'], s_train['bbox'])
# if iou > 0.0: #0.7
if matchings[i_test]['matching']:
# print("more matchings!")
matchings[i_test]['matching'].append(i_train)
matchings[i_test]['iou'].append(iou)
else:
matchings[i_test]['matching'] = [i_train]
matchings[i_test]['iou'] = [iou]
save_json(matchings, "./dataset/box_matchings_iou0.json")
return matchings
def match_bbox_2(test_dataset, prediction_dict):
########################calculate matchings########################
if os.path.exists("./dataset/box_matchings_with_iou.json"):
print("Found matches json, loading ...")
return load_json("./dataset/box_matchings_with_iou.json")
else:
print("No matches.json, creating ...")
matchings = {str(i): {"matching": [], "iou": [], "prediction_baseline_0": []} for i in range(len(test_dataset.anns))}
for i_test, s_test in tqdm(test_dataset.anns.items()):
for train_face, train_ann in prediction_dict.items():
if s_test['clip'] + '_' + s_test['img'] == train_ann['clip'] + '_' + train_ann['img']:
iou = calc_iou(s_test['bbox'], train_ann['bbox'])
# more than one match
if matchings[i_test]['matching']:
matchings[i_test]['matching'].append(train_face)
matchings[i_test]['iou'].append(iou)
matchings[i_test]['prediction_baseline_0'].append(train_ann['prediction_baseline_0'])
else:
matchings[i_test]['matching'] = [train_face] #matched faces
matchings[i_test]['iou'] = [iou] #iou of the matched faces
matchings[i_test]['prediction_baseline_0'] = [train_ann['prediction_baseline_0']] #predictions of the matched faces
save_json(matchings, "./dataset/box_matchings.json")
#add here the iou code:
to_be_deleted_ind = []
to_be_deleted_face = []
for i_test, s_test in tqdm(test_dataset.anns.items()):
if not matchings[i_test]["iou"]:
# this face is not matched with anything -> discard
to_be_deleted_ind.append(i_test)
to_be_deleted_face.append(s_test['face'])
else:
max_iou = np.max(np.array(matchings[i_test]["iou"]))
if max_iou == 0:
# this face is not matched with anything -> discard
to_be_deleted_ind.append(i_test)
to_be_deleted_face.append(s_test['face'])
save_json(to_be_deleted_ind, "./dataset/to_be_deleted_test_index.json")
save_json(to_be_deleted_face, "./dataset/to_be_deleted_test_face.json")
# update matchings:
valid_test_anns = {}