|
import faiss |
|
import numpy as np |
|
import torch |
|
import os, glob |
|
|
|
def get_results(features_path): |
|
print(features_path) |
|
embeddings_np = torch.load(features_path).numpy() |
|
all_cow_ids = torch.load("../big_model_inference/all_cow_ids.pt").numpy() |
|
|
|
|
|
mid_point = len(embeddings_np) // 2 |
|
|
|
embeddings_np_first_half = embeddings_np[:mid_point] |
|
embeddings_np_second_half = embeddings_np[mid_point:] |
|
|
|
all_cow_ids_first_half = all_cow_ids[:mid_point] |
|
all_cow_ids_second_half = all_cow_ids[mid_point:] |
|
|
|
|
|
d = embeddings_np_first_half.shape[1] |
|
nlist = 100 |
|
|
|
|
|
m = 8 |
|
nbits = 8 |
|
|
|
flat_index = faiss.IndexFlatL2(d) |
|
index_ivf = faiss.IndexIVFPQ(flat_index, d, nlist, m, nbits) |
|
index_ivf.nprobe = 10 |
|
index_ivf.train(embeddings_np_first_half) |
|
index_ivf.add(embeddings_np_first_half) |
|
|
|
k = 6 |
|
distances, indices = index_ivf.search(embeddings_np_second_half, k) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
top1_correct = 0 |
|
top5_correct = 0 |
|
|
|
for i, indices_row in enumerate(indices): |
|
query_id = all_cow_ids_second_half[i] |
|
|
|
|
|
retrieved_ids = [all_cow_ids_first_half[idx] for idx in indices_row] |
|
|
|
|
|
if retrieved_ids[0] == query_id: |
|
top1_correct += 1 |
|
|
|
|
|
if query_id in retrieved_ids[:5]: |
|
top5_correct += 1 |
|
|
|
|
|
top1_accuracy = top1_correct / len(embeddings_np_second_half) |
|
top5_accuracy = top5_correct / len(embeddings_np_second_half) |
|
|
|
print(f"Top-1 Accuracy: {top1_accuracy:.4f}") |
|
print(f"Top-5 Accuracy: {top5_accuracy:.4f}") |
|
|
|
directory = '../big_model_inference' |
|
pattern = os.path.join(directory, '*.pt') |
|
exclude_file = 'all_cow_ids.pt' |
|
for features_path in glob.glob(pattern): |
|
if os.path.basename(features_path) != exclude_file: |
|
get_results(features_path) |
|
|