-
Notifications
You must be signed in to change notification settings - Fork 0
/
knn.py
99 lines (75 loc) · 2.62 KB
/
knn.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
import argparse
import torch
import faiss
from tqdm import tqdm
from dinov2.models import DINOv2
from dinov2.data import LinProbDataset, build_linprob_transforms
from sklearn.linear_model import LogisticRegression
import numpy as np
parser = argparse.ArgumentParser()
parser.add_argument('--model-path', type=str)
parser.add_argument('--data-root', type=str)
parser.add_argument('--train-text', type=str)
parser.add_argument('--test-text', type=str)
parser.add_argument('--batch-size', default=32, type=int)
parser.add_argument('--num-workers', default=4, type=int)
def get_features(model, dataloader):
all_features = []
all_labels = []
with torch.no_grad():
for data in tqdm(dataloader):
outputs = model(data['pixel_values'].to(model.device))
features = outputs.x_norm_clstoken
all_features.append(features)
all_labels.append(data['labels'])
all_features = torch.cat(all_features).cpu().numpy()
all_labels = torch.cat(all_labels).cpu().numpy()
return all_features, all_labels
def main():
args = parser.parse_args()
model = DINOv2.from_pretrained(
args.model_path,
device_map='cuda',
torch_dtype=torch.float32,
)
model = model.eval()
transform = build_linprob_transforms(
img_size=model.config.img_size,
mean=(0.485, 0.456, 0.406),
std=(0.229, 0.224, 0.225),
)
train_dataset = LinProbDataset(
data_root=args.data_root,
filename=args.train_text,
transform=transform,
)
test_dataset = LinProbDataset(
data_root=args.data_root,
filename=args.test_text,
transform=transform,
)
train_dataloader = torch.utils.data.DataLoader(
train_dataset,
batch_size=args.batch_size,
shuffle=False,
drop_last=False,
num_workers=args.num_workers,
)
test_dataloader = torch.utils.data.DataLoader(
test_dataset,
batch_size=args.batch_size,
shuffle=False,
drop_last=False,
num_workers=args.num_workers,
)
train_features, train_labels = get_features(model.student.backbone, train_dataloader)
test_features, test_labels = get_features(model.student.backbone, test_dataloader)
index = faiss.IndexFlatL2(train_features.shape[-1])
index.add(train_features)
knn_dist, knn_idx = index.search(test_features, k=20)
preds = train_labels[knn_idx]
preds = np.array([np.bincount(pred).argmax() for pred in preds])
accuracy = (preds == test_labels).mean() * 100.0
print(f"Accuracy = {accuracy:.3f}")
if __name__ == '__main__':
main()