forked from gmberton/VPR-methods-evaluation
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvisualizations.py
More file actions
2273 lines (1846 loc) · 92.5 KB
/
visualizations.py
File metadata and controls
2273 lines (1846 loc) · 92.5 KB
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 numpy as np
from PIL import Image, ImageDraw, ImageFont
from tqdm import tqdm
import torch
from PIL import Image, ImageOps
import torchvision.transforms as tfm
import matplotlib.pyplot as plt
from sklearn.manifold import TSNE
from pathlib import Path
import faiss
import matplotlib.cm as cm
from scipy.cluster.hierarchy import dendrogram
from scipy.spatial.distance import squareform
import networkx as nx
from collections import defaultdict
import sys
# Height and width of a single image for visualization
IMG_HW = 512
TEXT_H = 175
FONTSIZE = 50
SPACE = 50 # Space between two images
def write_labels_to_image(labels=["text1", "text2"]):
"""Creates an image with text"""
font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", FONTSIZE)
img = Image.new("RGB", ((IMG_HW * len(labels)) + 50 * (len(labels) - 1), TEXT_H), (1, 1, 1))
d = ImageDraw.Draw(img)
for i, text in enumerate(labels):
lines = text.split('\n')
y_offset = 1
for line in lines:
_, _, w, h = d.textbbox((0, 0), line, font=font)
x_pos = (IMG_HW + SPACE) * i + IMG_HW // 2 - w // 2
d.text((x_pos, y_offset), line, fill=(0, 0, 0), font=font)
y_offset += h + 5 # Add some spacing between lines
return Image.fromarray(np.array(img)[:150] * 255) # Increased height for multi-line text
def draw_box(img, c=(0, 1, 0), thickness=20):
"""Draw a colored box around an image. Image should be a PIL.Image."""
assert isinstance(img, Image.Image)
img = tfm.ToTensor()(img)
assert len(img.shape) >= 2, f"{img.shape=}"
c = torch.tensor(c).type(torch.float).reshape(3, 1, 1)
img[..., :thickness, :] = c
img[..., -thickness:, :] = c
img[..., :, -thickness:] = c
img[..., :, :thickness] = c
return tfm.ToPILImage()(img)
def build_prediction_image(images_paths, preds_correct, confidences=None):
"""Build a row of images, where the first is the query and the rest are predictions.
For each image, if is_correct then draw a green/red box.
"""
assert len(images_paths) == len(preds_correct)
labels = ["Query"]
for i, is_correct in enumerate(preds_correct[1:]):
label = f"Pred{i}"
if confidences is not None and i < len(confidences) - 1:
# Add confidence score to label
conf = confidences[i + 1] # +1 because first is query
label += f"\nConf: {conf:.3f}"
if is_correct is not None:
label += f" - {is_correct}"
labels.append(label)
images = [Image.open(path).convert("RGB") for path in images_paths]
for img_idx, (img, is_correct) in enumerate(zip(images, preds_correct)):
if is_correct is None:
continue
color = (0, 1, 0) if is_correct else (1, 0, 0)
img = draw_box(img, color)
images[img_idx] = img
resized_images = [tfm.Resize(510, max_size=IMG_HW, antialias=True)(img) for img in images]
resized_images = [ImageOps.pad(img, (IMG_HW, IMG_HW), color='white') for img in images] # Apply padding to make them squared
total_h = len(resized_images)*IMG_HW + max(0,len(resized_images)-1)*SPACE # 2
concat_image = Image.new('RGB', (total_h, IMG_HW), (255, 255, 255))
y=0
for img in resized_images:
concat_image.paste(img, (y, 0))
y += IMG_HW + SPACE
try:
labels_image = write_labels_to_image(labels)
# Transform the images to np arrays for concatenation
final_image = Image.fromarray(np.concatenate((np.array(labels_image), np.array(concat_image)), axis=0))
except OSError: # Handle error in case of missing PIL ImageFont
final_image = concat_image
return final_image
def save_file_with_paths(query_path, preds_paths, positives_paths, output_path, use_labels=True, confidences=None):
file_content = []
file_content.append("Query path:")
file_content.append(query_path + "\n")
if confidences is not None:
file_content.append("Confidence scores:")
for i, conf in enumerate(confidences):
if conf is not None: # Skip None values (query)
file_content.append(f"Prediction {i-1}: {conf:.4f}")
file_content.append("") # Empty line
file_content.append("Predictions paths:")
file_content.append("\n".join(preds_paths) + "\n")
if use_labels:
file_content.append("Positives paths:")
file_content.append("\n".join(positives_paths) + "\n")
with open(output_path, "w") as file:
_ = file.write("\n".join(file_content))
def save_preds(predictions, eval_ds, log_dir, save_only_wrong_preds=None, use_labels=True, confidences=None):
"""For each query, save an image containing the query and its predictions,
and a file with the paths of the query, its predictions and its positives.
Parameters
----------
predictions : np.array of shape [num_queries x num_preds_to_viz], with the preds
for each query
eval_ds : TestDataset
log_dir : Path with the path to save the predictions
save_only_wrong_preds : bool, if True save only the wrongly predicted queries,
i.e. the ones where the first pred is uncorrect (further than 25 m)
confidences : np.array of shape [num_queries x num_preds_to_viz], with confidence
scores for each prediction (optional)
"""
if use_labels:
positives_per_query = eval_ds.get_positives()
viz_dir = log_dir / "preds"
viz_dir.mkdir()
for query_index, preds in enumerate(tqdm(predictions, desc=f"Saving preds in {viz_dir}")):
query_path = eval_ds.queries_paths[query_index]
list_of_images_paths = [query_path]
# List of None (query), True (correct preds) or False (wrong preds)
preds_correct = [None]
# Get confidence scores for this query if available
query_confidences = [None] if confidences is None else [None] # None for query itself
for pred_index, pred in enumerate(preds):
pred_path = eval_ds.database_paths[pred]
list_of_images_paths.append(pred_path)
if use_labels:
is_correct = pred in positives_per_query[query_index]
else:
is_correct = None
preds_correct.append(is_correct)
if confidences is not None:
query_confidences.append(confidences[query_index, pred_index])
if save_only_wrong_preds and preds_correct[1]:
continue
prediction_image = build_prediction_image(
list_of_images_paths,
preds_correct,
query_confidences if confidences is not None else None
)
pred_image_path = viz_dir / f"{query_index:03d}.jpg"
prediction_image.save(pred_image_path)
if use_labels:
positives_paths = [eval_ds.database_paths[idx] for idx in positives_per_query[query_index]]
else:
positives_paths = None
save_file_with_paths(
query_path=list_of_images_paths[0],
preds_paths=list_of_images_paths[1:],
positives_paths=positives_paths,
output_path=viz_dir / f"{query_index:03d}.txt",
use_labels=use_labels,
confidences=query_confidences if confidences is not None else None
)
def plot_tsne(database_descriptors, queries_descriptors, save_path, perplexity=30, n_iter=1000, random_state=42):
"""Create a t-SNE visualization of database and query descriptors.
Parameters
----------
database_descriptors : np.array of shape [num_database x descriptor_dim]
queries_descriptors : np.array of shape [num_queries x descriptor_dim]
save_path : Path or str, where to save the plot
perplexity : float, t-SNE perplexity parameter
n_iter : int, number of iterations for t-SNE
random_state : int, random seed for reproducibility
"""
# Combine all descriptors
all_descriptors = np.vstack([database_descriptors, queries_descriptors])
# Create labels (0 for database, 1 for queries)
labels = np.concatenate([
np.zeros(len(database_descriptors)),
np.ones(len(queries_descriptors))
])
print(f"Running t-SNE on {len(all_descriptors)} descriptors...")
# Run t-SNE
tsne = TSNE(n_components=2, perplexity=perplexity, n_iter=n_iter,
random_state=random_state, verbose=1)
embeddings = tsne.fit_transform(all_descriptors)
# Create the plot
plt.figure(figsize=(12, 10))
# Plot database points
db_embeddings = embeddings[labels == 0]
plt.scatter(db_embeddings[:, 0], db_embeddings[:, 1],
c='blue', alpha=0.6, s=50, label='Database', edgecolors='none')
# Plot query points
query_embeddings = embeddings[labels == 1]
plt.scatter(query_embeddings[:, 0], query_embeddings[:, 1],
c='red', alpha=0.8, s=100, label='Queries', edgecolors='black', linewidths=1)
plt.xlabel('t-SNE Component 1', fontsize=12)
plt.ylabel('t-SNE Component 2', fontsize=12)
plt.title('t-SNE Visualization of Image Descriptors', fontsize=14)
plt.legend(fontsize=12)
plt.grid(True, alpha=0.3)
# Save the plot
plt.tight_layout()
plt.savefig(save_path, dpi=300, bbox_inches='tight')
plt.close()
print(f"t-SNE plot saved to {save_path}")
# Also save the embeddings for potential further analysis
embeddings_path = Path(save_path).parent / "tsne_embeddings.npz"
np.savez(embeddings_path,
embeddings=embeddings,
labels=labels,
db_embeddings=db_embeddings,
query_embeddings=query_embeddings)
print(f"t-SNE embeddings saved to {embeddings_path}")
def plot_tsne_with_connections(database_descriptors, queries_descriptors, predictions,
save_path, num_connections=3, perplexity=30, n_iter=1000,
random_state=42):
"""Create an enhanced t-SNE visualization showing connections between queries and predictions.
Parameters
----------
database_descriptors : np.array of shape [num_database x descriptor_dim]
queries_descriptors : np.array of shape [num_queries x descriptor_dim]
predictions : np.array of shape [num_queries x num_predictions]
save_path : Path or str, where to save the plot
num_connections : int, number of top predictions to show connections for
perplexity : float, t-SNE perplexity parameter
n_iter : int, number of iterations for t-SNE
random_state : int, random seed for reproducibility
"""
# Combine all descriptors
all_descriptors = np.vstack([database_descriptors, queries_descriptors])
# Create labels (0 for database, 1 for queries)
labels = np.concatenate([
np.zeros(len(database_descriptors)),
np.ones(len(queries_descriptors))
])
print(f"Running t-SNE on {len(all_descriptors)} descriptors...")
# Run t-SNE
tsne = TSNE(n_components=2, perplexity=perplexity, n_iter=n_iter,
random_state=random_state, verbose=1)
embeddings = tsne.fit_transform(all_descriptors)
# Create the plot
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(24, 10))
# First subplot: Basic scatter plot
db_embeddings = embeddings[labels == 0]
query_embeddings = embeddings[labels == 1]
ax1.scatter(db_embeddings[:, 0], db_embeddings[:, 1],
c='blue', alpha=0.6, s=50, label='Database', edgecolors='none')
ax1.scatter(query_embeddings[:, 0], query_embeddings[:, 1],
c='red', alpha=0.8, s=100, label='Queries', edgecolors='black', linewidths=1)
ax1.set_xlabel('t-SNE Component 1', fontsize=12)
ax1.set_ylabel('t-SNE Component 2', fontsize=12)
ax1.set_title('t-SNE Visualization of Image Descriptors', fontsize=14)
ax1.legend(fontsize=12)
ax1.grid(True, alpha=0.3)
# Second subplot: With connections
ax2.scatter(db_embeddings[:, 0], db_embeddings[:, 1],
c='blue', alpha=0.3, s=30, label='Database', edgecolors='none')
ax2.scatter(query_embeddings[:, 0], query_embeddings[:, 1],
c='red', alpha=0.8, s=100, label='Queries', edgecolors='black', linewidths=1)
# Draw connections between queries and their top predictions
for query_idx in range(len(queries_descriptors)):
query_embedding = query_embeddings[query_idx]
# Get top predictions for this query
top_preds = predictions[query_idx, :num_connections]
for i, pred_idx in enumerate(top_preds):
pred_embedding = db_embeddings[pred_idx]
# Draw line with decreasing alpha for lower-ranked predictions
alpha = 0.6 * (1 - i / num_connections)
ax2.plot([query_embedding[0], pred_embedding[0]],
[query_embedding[1], pred_embedding[1]],
'gray', alpha=alpha, linewidth=1)
ax2.set_xlabel('t-SNE Component 1', fontsize=12)
ax2.set_ylabel('t-SNE Component 2', fontsize=12)
ax2.set_title(f'Query-Prediction Connections (Top {num_connections})', fontsize=14)
ax2.legend(fontsize=12)
ax2.grid(True, alpha=0.3)
# Save the plot
plt.tight_layout()
plt.savefig(save_path, dpi=300, bbox_inches='tight')
plt.close()
print(f"Enhanced t-SNE plot saved to {save_path}")
# Save embeddings
embeddings_path = Path(save_path).parent / "tsne_embeddings_enhanced.npz"
np.savez(embeddings_path,
embeddings=embeddings,
labels=labels,
db_embeddings=db_embeddings,
query_embeddings=query_embeddings,
predictions=predictions)
print(f"t-SNE embeddings saved to {embeddings_path}")
def plot_tsne_with_kmeans(database_descriptors, queries_descriptors, cluster_labels_db,
cluster_labels_queries, save_path, num_clusters,
perplexity=30, n_iter=1000, random_state=42):
"""Create a t-SNE visualization with k-means clustering results.
Parameters
----------
database_descriptors : np.array of shape [num_database x descriptor_dim]
queries_descriptors : np.array of shape [num_queries x descriptor_dim]
cluster_labels_db : np.array of shape [num_database], cluster assignments for database
cluster_labels_queries : np.array of shape [num_queries], cluster assignments for queries
save_path : Path or str, where to save the plot
num_clusters : int, number of clusters
perplexity : float, t-SNE perplexity parameter
n_iter : int, number of iterations for t-SNE
random_state : int, random seed for reproducibility
"""
# Combine all descriptors
all_descriptors = np.vstack([database_descriptors, queries_descriptors])
# Combine cluster labels
all_cluster_labels = np.concatenate([cluster_labels_db, cluster_labels_queries])
# Create labels (0 for database, 1 for queries)
data_type_labels = np.concatenate([
np.zeros(len(database_descriptors)),
np.ones(len(queries_descriptors))
])
print(f"Running t-SNE on {len(all_descriptors)} descriptors...")
# Run t-SNE
tsne = TSNE(n_components=2, perplexity=perplexity, n_iter=n_iter,
random_state=random_state, verbose=1)
embeddings = tsne.fit_transform(all_descriptors)
# Create the plot with subplots
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(24, 10))
# Get colors for clusters
colors = cm.tab20(np.linspace(0, 1, num_clusters))
# First subplot: Color by cluster
for cluster_id in range(num_clusters):
# Database points in this cluster
mask_db = (data_type_labels == 0) & (all_cluster_labels == cluster_id)
if np.any(mask_db):
ax1.scatter(embeddings[mask_db, 0], embeddings[mask_db, 1],
c=[colors[cluster_id]], alpha=0.6, s=50,
label=f'DB Cluster {cluster_id}', edgecolors='none')
# Query points in this cluster
mask_query = (data_type_labels == 1) & (all_cluster_labels == cluster_id)
if np.any(mask_query):
ax1.scatter(embeddings[mask_query, 0], embeddings[mask_query, 1],
c=[colors[cluster_id]], alpha=0.8, s=100,
marker='^', label=f'Query Cluster {cluster_id}',
edgecolors='black', linewidths=1)
ax1.set_xlabel('t-SNE Component 1', fontsize=12)
ax1.set_ylabel('t-SNE Component 2', fontsize=12)
ax1.set_title(f't-SNE Visualization with K-Means Clustering (K={num_clusters})', fontsize=14)
ax1.legend(bbox_to_anchor=(1.05, 1), loc='upper left', fontsize=10)
ax1.grid(True, alpha=0.3)
# Second subplot: Show cluster distribution
cluster_counts_db = np.bincount(cluster_labels_db, minlength=num_clusters)
cluster_counts_queries = np.bincount(cluster_labels_queries, minlength=num_clusters)
x = np.arange(num_clusters)
width = 0.35
ax2.bar(x - width/2, cluster_counts_db, width, label='Database', alpha=0.7)
ax2.bar(x + width/2, cluster_counts_queries, width, label='Queries', alpha=0.7)
ax2.set_xlabel('Cluster ID', fontsize=12)
ax2.set_ylabel('Number of Images', fontsize=12)
ax2.set_title('Distribution of Images across Clusters', fontsize=14)
ax2.set_xticks(x)
ax2.legend()
ax2.grid(True, alpha=0.3, axis='y')
# Save the plot
plt.tight_layout()
plt.savefig(save_path, dpi=300, bbox_inches='tight')
plt.close()
print(f"t-SNE with k-means plot saved to {save_path}")
# Save embeddings and cluster assignments
embeddings_path = Path(save_path).parent / "tsne_kmeans_embeddings.npz"
np.savez(embeddings_path,
embeddings=embeddings,
data_type_labels=data_type_labels,
cluster_labels=all_cluster_labels,
cluster_labels_db=cluster_labels_db,
cluster_labels_queries=cluster_labels_queries)
print(f"t-SNE embeddings and cluster labels saved to {embeddings_path}")
def save_images_by_cluster(database_paths, queries_paths, cluster_labels_db,
cluster_labels_queries, num_clusters, output_dir):
"""Save images organized by their cluster assignments.
Parameters
----------
database_paths : list of paths to database images
queries_paths : list of paths to query images
cluster_labels_db : np.array of cluster assignments for database images
cluster_labels_queries : np.array of cluster assignments for query images
num_clusters : int, number of clusters
output_dir : Path, directory to save the cluster directories
"""
output_dir = Path(output_dir)
output_dir.mkdir(exist_ok=True)
# Create a summary file
summary_file = output_dir / "cluster_summary.txt"
summary_lines = []
for cluster_id in range(num_clusters):
cluster_dir = output_dir / f"cluster_{cluster_id:02d}"
cluster_dir.mkdir(exist_ok=True)
# Create subdirectories for database and queries
db_dir = cluster_dir / "database"
query_dir = cluster_dir / "queries"
db_dir.mkdir(exist_ok=True)
query_dir.mkdir(exist_ok=True)
# Get indices for this cluster
db_indices = np.where(cluster_labels_db == cluster_id)[0]
query_indices = np.where(cluster_labels_queries == cluster_id)[0]
summary_lines.append(f"Cluster {cluster_id}:")
summary_lines.append(f" Database images: {len(db_indices)}")
summary_lines.append(f" Query images: {len(query_indices)}")
summary_lines.append("")
# Save database image paths
db_paths_file = cluster_dir / "database_paths.txt"
with open(db_paths_file, 'w') as f:
for idx in db_indices:
f.write(f"{database_paths[idx]}\n")
# Save query image paths
query_paths_file = cluster_dir / "query_paths.txt"
with open(query_paths_file, 'w') as f:
for idx in query_indices:
f.write(f"{queries_paths[idx]}\n")
# Create visualization of sample images from this cluster
create_cluster_visualization(database_paths, queries_paths, db_indices,
query_indices, cluster_id, cluster_dir)
# Write summary file
with open(summary_file, 'w') as f:
f.write('\n'.join(summary_lines))
print(f"Images organized by cluster saved to {output_dir}")
print(f"Cluster summary saved to {summary_file}")
def create_cluster_visualization(database_paths, queries_paths, db_indices,
query_indices, cluster_id, cluster_dir, max_images=None):
"""Create a visualization showing sample images from a cluster.
Parameters
----------
database_paths : list of all database image paths
queries_paths : list of all query image paths
db_indices : indices of database images in this cluster
query_indices : indices of query images in this cluster
cluster_id : int, cluster identifier
cluster_dir : Path, directory for this cluster
max_images : int or None, maximum number of images to show per category. If None, show all images.
"""
# Use all images if max_images is None
if max_images is None:
db_sample = db_indices
query_sample = query_indices
else:
db_sample = db_indices[:max_images]
query_sample = query_indices[:max_images]
# Calculate grid dimensions
n_db = len(db_sample)
n_query = len(query_sample)
if n_db == 0 and n_query == 0:
return
# Adaptive grid sizing based on number of images
total_images = n_db + n_query
if total_images <= 10:
img_size = 256
max_cols = 5
elif total_images <= 50:
img_size = 150
max_cols = 10
elif total_images <= 100:
img_size = 100
max_cols = 15
else:
img_size = 75
max_cols = 20
# Calculate grid dimensions
n_cols = min(max_cols, max(n_db, n_query))
n_rows = 2 # One row for database, one for queries
# Create the visualization
fig_width = min(30, n_cols * (img_size / 100)) # Scale figure width
fig_height = n_rows * (img_size / 100) + 1 # Scale figure height
fig, axes = plt.subplots(n_rows, n_cols, figsize=(fig_width, fig_height))
# Handle case where axes is 1D
if n_cols == 1:
axes = axes.reshape(-1, 1)
elif n_rows == 1:
axes = axes.reshape(1, -1)
# Display database images
for i in range(n_cols):
# Database row
if i < n_db:
img_path = database_paths[db_sample[i]]
try:
img = Image.open(img_path).convert('RGB')
img_resized = tfm.Resize((img_size, img_size), antialias=True)(img)
axes[0, i].imshow(img_resized)
axes[0, i].set_title(f'DB {db_sample[i]}', fontsize=max(6, 8 * (100 / img_size)))
except Exception as e:
axes[0, i].text(0.5, 0.5, 'Error', ha='center', va='center', transform=axes[0, i].transAxes)
else:
axes[0, i].axis('off')
axes[0, i].set_xticks([])
axes[0, i].set_yticks([])
# Query row
if i < n_query:
img_path = queries_paths[query_sample[i]]
try:
img = Image.open(img_path).convert('RGB')
img_resized = tfm.Resize((img_size, img_size), antialias=True)(img)
axes[1, i].imshow(img_resized)
axes[1, i].set_title(f'Q {query_sample[i]}', fontsize=max(6, 8 * (100 / img_size)))
except Exception as e:
axes[1, i].text(0.5, 0.5, 'Error', ha='center', va='center', transform=axes[1, i].transAxes)
else:
axes[1, i].axis('off')
axes[1, i].set_xticks([])
axes[1, i].set_yticks([])
# Add row labels
if n_db > 0:
axes[0, 0].set_ylabel('Database', fontsize=10, rotation=90, va='center')
if n_query > 0:
axes[1, 0].set_ylabel('Queries', fontsize=10, rotation=90, va='center')
plt.suptitle(f'Cluster {cluster_id} Images\n(DB: {len(db_indices)} images, Queries: {len(query_indices)} images)',
fontsize=12)
plt.tight_layout()
# Save the visualization
viz_path = cluster_dir / f'cluster_{cluster_id}_grid.jpg'
plt.savefig(viz_path, dpi=150, bbox_inches='tight')
plt.close()
def plot_tsne_with_hdbscan(database_descriptors, queries_descriptors, cluster_labels_db,
cluster_labels_queries, save_path,
perplexity=30, n_iter=1000, random_state=42):
"""Create a t-SNE visualization with HDBSCAN clustering results.
Parameters
----------
database_descriptors : np.array of shape [num_database x descriptor_dim]
queries_descriptors : np.array of shape [num_queries x descriptor_dim]
cluster_labels_db : np.array of shape [num_database], cluster assignments for database
cluster_labels_queries : np.array of shape [num_queries], cluster assignments for queries
save_path : Path or str, where to save the plot
perplexity : float, t-SNE perplexity parameter
n_iter : int, number of iterations for t-SNE
random_state : int, random seed for reproducibility
"""
# Combine all descriptors
all_descriptors = np.vstack([database_descriptors, queries_descriptors])
# Combine cluster labels
all_cluster_labels = np.concatenate([cluster_labels_db, cluster_labels_queries])
# Create labels (0 for database, 1 for queries)
data_type_labels = np.concatenate([
np.zeros(len(database_descriptors)),
np.ones(len(queries_descriptors))
])
print(f"Running t-SNE on {len(all_descriptors)} descriptors...")
# Run t-SNE
tsne = TSNE(n_components=2, perplexity=perplexity, n_iter=n_iter,
random_state=random_state, verbose=1)
embeddings = tsne.fit_transform(all_descriptors)
# Create the plot with subplots
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(24, 10))
# Get unique cluster labels (excluding noise points -1)
unique_labels = np.unique(all_cluster_labels)
n_clusters = len(unique_labels[unique_labels != -1])
# Get colors for clusters
colors = cm.tab20(np.linspace(0, 1, max(n_clusters, 1)))
# First subplot: Color by cluster
for i, cluster_id in enumerate(unique_labels):
if cluster_id == -1:
# Noise points in gray
color = 'gray'
label_prefix = 'Noise'
alpha_db = 0.3
alpha_query = 0.5
else:
color = colors[i % len(colors)]
label_prefix = f'Cluster {cluster_id}'
alpha_db = 0.6
alpha_query = 0.8
# Database points in this cluster
mask_db = (data_type_labels == 0) & (all_cluster_labels == cluster_id)
if np.any(mask_db):
ax1.scatter(embeddings[mask_db, 0], embeddings[mask_db, 1],
c=[color], alpha=alpha_db, s=50,
label=f'DB {label_prefix}', edgecolors='none')
# Query points in this cluster
mask_query = (data_type_labels == 1) & (all_cluster_labels == cluster_id)
if np.any(mask_query):
ax1.scatter(embeddings[mask_query, 0], embeddings[mask_query, 1],
c=[color], alpha=alpha_query, s=100,
marker='^', label=f'Query {label_prefix}',
edgecolors='black', linewidths=1)
ax1.set_xlabel('t-SNE Component 1', fontsize=12)
ax1.set_ylabel('t-SNE Component 2', fontsize=12)
ax1.set_title(f't-SNE Visualization with HDBSCAN Clustering ({n_clusters} clusters found)', fontsize=14)
ax1.legend(bbox_to_anchor=(1.05, 1), loc='upper left', fontsize=10)
ax1.grid(True, alpha=0.3)
# Second subplot: Show cluster distribution
unique_labels_no_noise = unique_labels[unique_labels != -1]
# Count points in each cluster (including noise)
cluster_counts_db = []
cluster_counts_queries = []
cluster_labels_for_plot = []
for cluster_id in unique_labels:
db_count = np.sum((cluster_labels_db == cluster_id))
query_count = np.sum((cluster_labels_queries == cluster_id))
if db_count > 0 or query_count > 0:
cluster_counts_db.append(db_count)
cluster_counts_queries.append(query_count)
cluster_labels_for_plot.append(f'Noise' if cluster_id == -1 else f'C{cluster_id}')
x = np.arange(len(cluster_labels_for_plot))
width = 0.35
ax2.bar(x - width/2, cluster_counts_db, width, label='Database', alpha=0.7)
ax2.bar(x + width/2, cluster_counts_queries, width, label='Queries', alpha=0.7)
ax2.set_xlabel('Cluster', fontsize=12)
ax2.set_ylabel('Number of Images', fontsize=12)
ax2.set_title('Distribution of Images across HDBSCAN Clusters', fontsize=14)
ax2.set_xticks(x)
ax2.set_xticklabels(cluster_labels_for_plot, rotation=45 if len(cluster_labels_for_plot) > 10 else 0)
ax2.legend()
ax2.grid(True, alpha=0.3, axis='y')
# Save the plot
plt.tight_layout()
plt.savefig(save_path, dpi=300, bbox_inches='tight')
plt.close()
print(f"t-SNE with HDBSCAN plot saved to {save_path}")
# Save embeddings and cluster assignments
embeddings_path = Path(save_path).parent / "tsne_hdbscan_embeddings.npz"
np.savez(embeddings_path,
embeddings=embeddings,
data_type_labels=data_type_labels,
cluster_labels=all_cluster_labels,
cluster_labels_db=cluster_labels_db,
cluster_labels_queries=cluster_labels_queries)
print(f"t-SNE embeddings and cluster labels saved to {embeddings_path}")
def save_hdbscan_images_by_cluster(database_paths, queries_paths, cluster_labels_db,
cluster_labels_queries, output_dir):
"""Save images organized by their HDBSCAN cluster assignments.
Parameters
----------
database_paths : list of paths to database images
queries_paths : list of paths to query images
cluster_labels_db : np.array of cluster assignments for database images
cluster_labels_queries : np.array of cluster assignments for query images
output_dir : Path, directory to save the cluster directories
"""
output_dir = Path(output_dir)
output_dir.mkdir(exist_ok=True)
# Get unique cluster labels
all_labels = np.concatenate([cluster_labels_db, cluster_labels_queries])
unique_labels = np.unique(all_labels)
# Create a summary file
summary_file = output_dir / "hdbscan_cluster_summary.txt"
summary_lines = []
summary_lines.append(f"HDBSCAN Clustering Results")
summary_lines.append(f"Total clusters found: {len(unique_labels[unique_labels != -1])}")
summary_lines.append("")
for cluster_id in unique_labels:
if cluster_id == -1:
cluster_name = "noise"
else:
cluster_name = f"cluster_{cluster_id:02d}"
cluster_dir = output_dir / cluster_name
cluster_dir.mkdir(exist_ok=True)
# Create subdirectories for database and queries
db_dir = cluster_dir / "database"
query_dir = cluster_dir / "queries"
db_dir.mkdir(exist_ok=True)
query_dir.mkdir(exist_ok=True)
# Get indices for this cluster
db_indices = np.where(cluster_labels_db == cluster_id)[0]
query_indices = np.where(cluster_labels_queries == cluster_id)[0]
if cluster_id == -1:
summary_lines.append(f"Noise points:")
else:
summary_lines.append(f"Cluster {cluster_id}:")
summary_lines.append(f" Database images: {len(db_indices)}")
summary_lines.append(f" Query images: {len(query_indices)}")
summary_lines.append("")
# Save database image paths
db_paths_file = cluster_dir / "database_paths.txt"
with open(db_paths_file, 'w') as f:
for idx in db_indices:
f.write(f"{database_paths[idx]}\n")
# Save query image paths
query_paths_file = cluster_dir / "query_paths.txt"
with open(query_paths_file, 'w') as f:
for idx in query_indices:
f.write(f"{queries_paths[idx]}\n")
# Create visualization of sample images from this cluster
create_cluster_visualization(database_paths, queries_paths, db_indices,
query_indices, cluster_id, cluster_dir)
# Write summary file
with open(summary_file, 'w') as f:
f.write('\n'.join(summary_lines))
print(f"Images organized by HDBSCAN clusters saved to {output_dir}")
print(f"Cluster summary saved to {summary_file}")
def plot_hierarchical_dendrogram(linkage_matrix, save_path, distance_threshold=0.5,
labels=None, title_suffix=""):
"""Create a dendrogram visualization for hierarchical clustering.
Parameters
----------
linkage_matrix : np.array, linkage matrix from scipy hierarchical clustering
save_path : Path or str, where to save the plot
distance_threshold : float, distance threshold for cutting the dendrogram
labels : list, optional labels for leaves
title_suffix : str, additional text for the title
"""
plt.figure(figsize=(20, 10))
# Create dendrogram
dendrogram_result = dendrogram(
linkage_matrix,
labels=labels,
color_threshold=distance_threshold,
above_threshold_color='gray',
leaf_rotation=90,
leaf_font_size=8
)
# Add threshold line
plt.axhline(y=distance_threshold, c='red', linestyle='--',
label=f'Distance threshold = {distance_threshold}')
plt.xlabel('Sample Index', fontsize=12)
plt.ylabel('Cosine Distance', fontsize=12)
plt.title(f'Hierarchical Clustering Dendrogram{title_suffix}', fontsize=14)
plt.legend(fontsize=12)
plt.grid(True, alpha=0.3, axis='y')
plt.tight_layout()
plt.savefig(save_path, dpi=300, bbox_inches='tight')
plt.close()
print(f"Dendrogram saved to {save_path}")
return dendrogram_result
def plot_tsne_with_hierarchical(database_descriptors, queries_descriptors,
cluster_labels_db, cluster_labels_queries,
save_path, linkage_matrix=None, distance_threshold=0.5,
perplexity=30, n_iter=1000, random_state=42):
"""Create a t-SNE visualization with hierarchical clustering results.
Parameters
----------
database_descriptors : np.array of shape [num_database x descriptor_dim]
queries_descriptors : np.array of shape [num_queries x descriptor_dim]
cluster_labels_db : np.array of shape [num_database], cluster assignments for database
cluster_labels_queries : np.array of shape [num_queries], cluster assignments for queries
save_path : Path or str, where to save the plot
linkage_matrix : np.array, optional linkage matrix for showing dendrogram
distance_threshold : float, distance threshold used for clustering
perplexity : float, t-SNE perplexity parameter
n_iter : int, number of iterations for t-SNE
random_state : int, random seed for reproducibility
"""
# Combine all descriptors
all_descriptors = np.vstack([database_descriptors, queries_descriptors])
# Combine cluster labels
all_cluster_labels = np.concatenate([cluster_labels_db, cluster_labels_queries])
# Create labels (0 for database, 1 for queries)
data_type_labels = np.concatenate([
np.zeros(len(database_descriptors)),
np.ones(len(queries_descriptors))
])
print(f"Running t-SNE on {len(all_descriptors)} descriptors...")
# Run t-SNE
tsne = TSNE(n_components=2, perplexity=perplexity, n_iter=n_iter,
random_state=random_state, verbose=1)
embeddings = tsne.fit_transform(all_descriptors)
# Determine number of clusters
unique_clusters = np.unique(all_cluster_labels)
n_clusters = len(unique_clusters)
# Create figure with subplots
if linkage_matrix is not None:
fig = plt.figure(figsize=(36, 10))
gs = fig.add_gridspec(1, 3, width_ratios=[1, 1, 1.5])
ax1 = fig.add_subplot(gs[0])
ax2 = fig.add_subplot(gs[1])
ax3 = fig.add_subplot(gs[2])
else:
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(24, 10))
# Get colors for clusters
if n_clusters <= 20:
colors = cm.tab20(np.linspace(0, 1, n_clusters))
else:
colors = cm.gist_rainbow(np.linspace(0, 1, n_clusters))
# First subplot: Color by cluster
for i, cluster_id in enumerate(unique_clusters):
# Database points in this cluster
mask_db = (data_type_labels == 0) & (all_cluster_labels == cluster_id)
if np.any(mask_db):
ax1.scatter(embeddings[mask_db, 0], embeddings[mask_db, 1],
c=[colors[i]], alpha=0.6, s=50,
label=f'DB Cluster {cluster_id}', edgecolors='none')
# Query points in this cluster
mask_query = (data_type_labels == 1) & (all_cluster_labels == cluster_id)
if np.any(mask_query):
ax1.scatter(embeddings[mask_query, 0], embeddings[mask_query, 1],
c=[colors[i]], alpha=0.8, s=100,
marker='^', label=f'Query Cluster {cluster_id}',
edgecolors='black', linewidths=1)
ax1.set_xlabel('t-SNE Component 1', fontsize=12)
ax1.set_ylabel('t-SNE Component 2', fontsize=12)
ax1.set_title(f't-SNE with Hierarchical Clustering\n(threshold={distance_threshold}, {n_clusters} clusters)',
fontsize=14)
ax1.legend(bbox_to_anchor=(1.05, 1), loc='upper left', fontsize=8)
ax1.grid(True, alpha=0.3)
# Second subplot: Show cluster distribution
cluster_counts_db = np.bincount(cluster_labels_db, minlength=n_clusters)
cluster_counts_queries = np.bincount(cluster_labels_queries, minlength=n_clusters)
x = np.arange(n_clusters)
width = 0.35
ax2.bar(x - width/2, cluster_counts_db, width, label='Database', alpha=0.7)
ax2.bar(x + width/2, cluster_counts_queries, width, label='Queries', alpha=0.7)
ax2.set_xlabel('Cluster ID', fontsize=12)
ax2.set_ylabel('Number of Images', fontsize=12)
ax2.set_title('Distribution of Images across Clusters', fontsize=14)
ax2.set_xticks(x)
ax2.legend()
ax2.grid(True, alpha=0.3, axis='y')
# Third subplot: Mini dendrogram if linkage matrix provided
if linkage_matrix is not None:
dendrogram(
linkage_matrix,
ax=ax3,
color_threshold=distance_threshold,
above_threshold_color='gray',
no_labels=True
)
ax3.axhline(y=distance_threshold, c='red', linestyle='--',
label=f'Threshold = {distance_threshold}')
ax3.set_xlabel('Sample Index', fontsize=10)
ax3.set_ylabel('Cosine Distance', fontsize=10)
ax3.set_title('Hierarchical Clustering Dendrogram', fontsize=12)
ax3.legend(fontsize=10)
ax3.grid(True, alpha=0.3, axis='y')
# Save the plot
plt.tight_layout()
plt.savefig(save_path, dpi=300, bbox_inches='tight')
plt.close()
print(f"t-SNE with hierarchical clustering plot saved to {save_path}")
# Save embeddings and cluster assignments
embeddings_path = Path(save_path).parent / "tsne_hierarchical_embeddings.npz"
np.savez(embeddings_path,
embeddings=embeddings,
data_type_labels=data_type_labels,
cluster_labels=all_cluster_labels,
cluster_labels_db=cluster_labels_db,
cluster_labels_queries=cluster_labels_queries)
print(f"t-SNE embeddings and cluster labels saved to {embeddings_path}")
def save_hierarchical_images_by_cluster(database_paths, queries_paths, cluster_labels_db,
cluster_labels_queries, output_dir,
distance_threshold=0.5):
"""Save images organized by their hierarchical cluster assignments.