-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathevaluate.py
152 lines (127 loc) · 4.62 KB
/
evaluate.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
#!/usr/bin/python
# -*- encoding: utf-8 -*-
import sys
import os
import os.path as osp
import logging
import pickle
from tqdm import tqdm
import numpy as np
import torch
from backbone import Network_D
from torch.utils.data import DataLoader
from market1501 import Market1501
FORMAT = '%(levelname)s %(filename)s(%(lineno)d): %(message)s'
logging.basicConfig(level=logging.INFO, format=FORMAT, stream=sys.stdout)
logger = logging.getLogger(__name__)
def embed():
## load checkpoint
res_pth = './res'
mod_pth = osp.join(res_pth, 'model_final.pkl')
net = Network_D()
net.load_state_dict(torch.load(mod_pth))
net.cuda()
net.eval()
## data loader
query_set = Market1501('./dataset/Market-1501-v15.09.15/query',
is_train = False)
gallery_set = Market1501('./dataset/Market-1501-v15.09.15/bounding_box_test',
is_train = False)
query_loader = DataLoader(query_set,
batch_size = 32,
num_workers = 4,
drop_last = False)
gallery_loader = DataLoader(gallery_set,
batch_size = 32,
num_workers = 4,
drop_last = False)
## embed
logger.info('embedding query set ...')
query_pids = []
query_camids = []
query_embds = []
for i, (im, _, ids) in enumerate(tqdm(query_loader)):
embds = []
for crop in im:
crop = crop.cuda()
embds.append(net(crop).detach().cpu().numpy())
embed = sum(embds) / len(embds)
pid = ids[0].numpy()
camid = ids[1].numpy()
query_embds.append(embed)
query_pids.extend(pid)
query_camids.extend(camid)
query_embds = np.vstack(query_embds)
query_pids = np.array(query_pids)
query_camids = np.array(query_camids)
logger.info('embedding gallery set ...')
gallery_pids = []
gallery_camids = []
gallery_embds = []
for i, (im, _, ids) in enumerate(tqdm(gallery_loader)):
embds = []
for crop in im:
crop = crop.cuda()
embds.append(net(crop).detach().cpu().numpy())
embed = sum(embds) / len(embds)
pid = ids[0].numpy()
camid = ids[1].numpy()
gallery_embds.append(embed)
gallery_pids.extend(pid)
gallery_camids.extend(camid)
gallery_embds = np.vstack(gallery_embds)
gallery_pids = np.array(gallery_pids)
gallery_camids = np.array(gallery_camids)
## dump embeds results
embd_res = (query_embds, query_pids, query_camids, gallery_embds, gallery_pids, gallery_camids)
with open('./res/embds.pkl', 'wb') as fw:
pickle.dump(embd_res, fw)
logger.info('embedding done, dump to: ./res/embds.pkl')
return embd_res
def evaluate(embd_res, cmc_max_rank = 1):
query_embds, query_pids, query_camids, gallery_embds, gallery_pids, gallery_camids = embd_res
## compute distance matrix
logger.info('compute distance matrix')
dist_mtx = np.matmul(query_embds, gallery_embds.T)
dist_mtx = 1.0 / (dist_mtx + 1)
n_q, n_g = dist_mtx.shape
logger.info('start evaluating ...')
indices = np.argsort(dist_mtx, axis = 1)
matches = gallery_pids[indices] == query_pids[:, np.newaxis]
matches = matches.astype(np.int32)
all_aps = []
all_cmcs = []
for query_idx in tqdm(range(n_q)):
query_pid = query_pids[query_idx]
query_camid = query_camids[query_idx]
## exclude duplicated gallery pictures
order = indices[query_idx]
pid_diff = gallery_pids[order] != query_pid
camid_diff = gallery_camids[order] != query_camid
useful = gallery_pids[order] != -1
keep = np.logical_or(pid_diff, camid_diff)
keep = np.logical_and(keep, useful)
match = matches[query_idx][keep]
if not np.any(match): continue
## compute cmc
cmc = match.cumsum()
cmc[cmc > 1] = 1
all_cmcs.append(cmc[:cmc_max_rank])
## compute map
num_real = match.sum()
match_cum = match.cumsum()
match_cum = [el / (1.0 + i) for i, el in enumerate(match_cum)]
match_cum = np.array(match_cum) * match
ap = match_cum.sum() / num_real
all_aps.append(ap)
assert len(all_aps) > 0, "NO QUERRY APPEARS IN THE GALLERY"
mAP = sum(all_aps) / len(all_aps)
all_cmcs = np.array(all_cmcs, dtype = np.float32)
cmc = np.mean(all_cmcs, axis = 0)
return cmc, mAP
if __name__ == '__main__':
embd_res = embed()
with open('./res/embds.pkl', 'rb') as fr:
embd_res = pickle.load(fr)
cmc, mAP = evaluate(embd_res)
print('cmc is: {}, map is: {}'.format(cmc, mAP))