-
Notifications
You must be signed in to change notification settings - Fork 13
/
engine.py
143 lines (113 loc) · 4.98 KB
/
engine.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
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: CC-BY-NC-4.0
import time
from datetime import timedelta
import faiss
import numpy as np
import torch
import torch.nn as nn
from utils import utils
def validate(val_loader, model, criterion, args):
batch_time = utils.AverageMeter('Time', ':6.3f')
losses = utils.AverageMeter('Loss', ':.4e')
top1 = utils.AverageMeter('Acc@1', ':6.2f')
top5 = utils.AverageMeter('Acc@5', ':6.2f')
progress = utils.ProgressMeter(
len(val_loader),
[batch_time, losses, top1, top5],
prefix='Test: ')
# switch to evaluate mode
model.eval()
with torch.no_grad():
end = time.time()
for i, (images, target) in enumerate(val_loader):
if args.gpu is not None:
images = images.cuda(args.gpu, non_blocking=True)
target = target.cuda(args.gpu, non_blocking=True)
# compute output
output = model(images)
loss = criterion(output, target)
# measure accuracy and record loss
acc1, acc5 = utils.accuracy(output, target, topk=(1, 5))
losses.update(loss.item(), images.size(0))
top1.update(acc1[0], images.size(0))
top5.update(acc5[0], images.size(0))
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
progress.display(i)
# TODO: this should also be done with the ProgressMeter
print(' * Acc@1 {top1.avg:.3f} Acc@5 {top5.avg:.3f} Loss {loss.avg:.4f}'
.format(top1=top1, top5=top5, loss=losses))
return top1.avg
def ss_validate(val_loader_base, val_loader_query, model, args):
print("start KNN evaluation with key size={} and query size={}".format(
len(val_loader_base.dataset.targets), len(val_loader_query.dataset.targets)))
batch_time_key = utils.AverageMeter('Time', ':6.3f')
batch_time_query = utils.AverageMeter('Time', ':6.3f')
# switch to evaluate mode
model.eval()
feats_base = []
target_base = []
feats_query = []
target_query = []
with torch.no_grad():
start = time.time()
end = time.time()
# Memory features
for i, (images, target) in enumerate(val_loader_base):
if args.gpu is not None:
images = images.cuda(args.gpu, non_blocking=True)
target = target.cuda(args.gpu, non_blocking=True)
# compute features
feats = model(images)
# L2 normalization
feats = nn.functional.normalize(feats, dim=1)
feats_base.append(feats)
target_base.append(target)
# measure elapsed time
batch_time_key.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
print('Extracting key features: [{0}/{1}]\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})'.format(
i, len(val_loader_base), batch_time=batch_time_key))
end = time.time()
for i, (images, target) in enumerate(val_loader_query):
if args.gpu is not None:
images = images.cuda(args.gpu, non_blocking=True)
target = target.cuda(args.gpu, non_blocking=True)
# compute features
feats = model(images)
# L2 normalization
feats = nn.functional.normalize(feats, dim=1)
feats_query.append(feats)
target_query.append(target)
# measure elapsed time
batch_time_query.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
print('Extracting query features: [{0}/{1}]\t'
'Time {batch_time.val:.3f} ({batch_time.avg:.3f})'.format(
i, len(val_loader_query), batch_time=batch_time_query))
feats_base = torch.cat(feats_base, dim=0)
target_base = torch.cat(target_base, dim=0)
feats_query = torch.cat(feats_query, dim=0)
target_query = torch.cat(target_query, dim=0)
feats_base = feats_base.detach().cpu().numpy()
target_base = target_base.detach().cpu().numpy()
feats_query = feats_query.detach().cpu().numpy()
target_query = target_query.detach().cpu().numpy()
feat_time = time.time() - start
# KNN search
index = faiss.IndexFlatL2(feats_base.shape[1])
index.add(feats_base)
D, I = index.search(feats_query, args.num_nn)
preds = np.array([np.bincount(target_base[n]).argmax() for n in I])
NN_acc = (preds == target_query).sum() / len(target_query) * 100.0
knn_time = time.time() - start - feat_time
print("finished KNN evaluation, feature time: {}, knn time: {}".format(
timedelta(seconds=feat_time), timedelta(seconds=knn_time)))
print(' * NN Acc@1 {:.3f}'.format(NN_acc))
return NN_acc