-
Notifications
You must be signed in to change notification settings - Fork 4
/
retrieve-many.py
336 lines (257 loc) · 9.6 KB
/
retrieve-many.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
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
import argparse
import os
import json
import faiss
import numpy as np
import pandas as pd
from data import create_multi_splits
from validate import L2norm
from validate import retrieve, KNN, score
# Training settings
parser = argparse.ArgumentParser(description='PyTorch SBIR')
parser.add_argument('--dir-path', type=str, default='exp', metavar='ED',
help='directory with domainnet models')
parser.add_argument('--new-data-path', type=str, default='', metavar='ED',
help='overwrite data path')
parser.add_argument('--eval', type=str, required=True, metavar='ED',
help='many2any|any2many')
args = parser.parse_args()
GROUPS = 500
SEED = 1234
def get_config():
# iterate over folders in the directory
configs = {}
for path in os.listdir(args.dir_path):
fname = os.path.join(args.dir_path, path, 'config.json')
if os.path.isfile(fname):
with open(fname) as f:
tmp = json.load(f)
if tmp['mode'] == 'im':
configs[tmp['domain']] = tmp
configs[tmp['domain']]['working_path'] = os.path.join(
args.dir_path, path)
if not args.new_data_path == '':
configs[tmp['domain']]['data_dir'] = args.new_data_path
else:
configs['quickdraw'] = tmp
configs['quickdraw']['working_path'] = os.path.join(
args.dir_path, path)
if not args.new_data_path == '':
configs['quickdraw']['data_dir'] = args.new_data_path
return configs
def get_splits(configs):
keys = configs.keys()
keys.sort()
fpaths = []
domains = []
y = []
for key in keys:
# get data splits
df_dir = os.path.join('aux', 'data', configs[key]['dataset'])
splits = create_multi_splits(df_dir, configs[key]['domain'])
if key == 'quickdraw':
fpaths.extend(splits['sk']['test'].index.values)
domains.extend(splits['sk']['test']['domain'].values)
y.extend(splits['sk']['test']['cat'].values)
else:
fpaths.extend(splits['im']['test'].index.values)
domains.extend(splits['im']['test']['domain'].values)
y.extend(splits['im']['test']['cat'].values)
df = pd.DataFrame({'domain': domains, 'cat': y}, index=fpaths)
return df
def read_data(fpath):
data = np.load(fpath)
return data['features'], data['labels']
def mix_queries(base, complement, alpha=0.5):
idx = sample_complement(base['y'], complement['y'])
mixture = alpha * base['x'] + (1-alpha) * complement['x'][idx, :]
return mixture, idx
def sample_complement(y_base, y_complement):
np.random.seed(SEED)
idx = []
for y in y_base:
cond_idx = np.argwhere(y_complement == y).squeeze()
idx.append(np.random.choice(cond_idx))
return idx
def many2any_retrieval(configs, sources=['quickdraw', 'real']):
keys = configs.keys()
keys.sort()
source_data = {}
for domain in sources:
dirname = configs[domain]['working_path']
fpath = os.path.join(dirname, 'features.npz')
x, y = read_data(fpath)
source_data[domain] = {}
source_data[domain]['x'] = x
source_data[domain]['y'] = y
# save images that have been mixed, such that they don't get retrived
x_src, idx = mix_queries(source_data[sources[0]], source_data[sources[1]])
y_src = source_data[sources[0]]['y']
np.save('plop.npy', idx)
res = {}
for domain in keys:
dirname = configs[domain]['working_path']
fpath = os.path.join(dirname, 'features.npz')
x_tgt, y_tgt = read_data(fpath)
if sources[0] == domain and sources[1] == domain:
pass
else:
print('\nRetrieval from %s+%s to %s' %
(sources[0], sources[1], domain))
if domain == sources[1]:
do_mixture = True
else:
do_mixture = False
tmp = cross_domain_retrieval(
x_src, y_src, x_tgt, y_tgt,
zeroshot=configs[domain]['overwrite'],
mixture=do_mixture)
res[domain] = tmp
os.remove('plop.npy')
def get_data(configs):
keys = configs.keys()
keys.sort()
feats = []
labels = []
domains = []
for i, key in enumerate(keys):
dirname = configs[key]['working_path']
fpath = os.path.join(dirname, 'features.npz')
data = np.load(fpath)
nsamples = len(data['labels'])
feats.extend(data['features'])
labels.extend(data['labels'])
domains.extend([key] * nsamples)
return feats, labels, domains
def one2many_retrieve_intent_aware(feats, labels, domains, splits,
source='quickdraw',
zeroshot=False):
cond = np.asarray(domains) == source
x_src = np.asarray(feats)[cond, :]
y_src = np.asarray(labels)[cond]
x_tgt = np.asarray(feats)[~cond, :]
y_tgt = np.asarray(labels)[~cond]
d_tgt = np.asarray(domains)[~cond]
# KNN
g_src_x = KNN(x_src, x_tgt, K=1, mode='ones')
if zeroshot:
alpha = 0.7
else:
alpha = 0.4
x_src = slerp(alpha, L2norm(x_src), L2norm(g_src_x))
idx = myretrieve(x_src, x_tgt, topK=100)
yd_tgt = np.char.add(y_tgt.astype(d_tgt.dtype), d_tgt)
domains = np.unique(d_tgt)
categories = np.unique(y_tgt)
# compute occurrences of every category per domain
occ = []
for d in domains:
occ_inner = []
for c in categories:
cond = np.logical_and(d_tgt == d, y_tgt == c)
occ_inner.append(np.sum(cond))
occ.append(occ_inner)
occ = np.asarray(occ, dtype=np.float)
# normalize occurences
occ /= np.sum(occ, axis=0)
import multiprocessing as mp
from metrics import average_precision
# compute intent-aware mAP per domain
mAP_ia = []
for d in domains:
yd_src = np.char.add(y_src.astype(d_tgt.dtype), d)
res = np.char.equal(yd_tgt[idx], yd_src[:, None])
pool = mp.Pool(processes=10)
results = [pool.apply_async(average_precision, args=(r,)) for r in res]
mAP = np.asarray([p.get() for p in results])
pool.close()
mAP_ia.append(mAP)
print('%s: %.3f' % (d, np.mean(mAP)))
mAP_ia = np.asarray(mAP_ia)
mAP_ia_final = (occ[:, y_src] * mAP_ia).sum(0).mean()
print('mAP-IA: %.3f' % mAP_ia_final)
return idx
def cross_domain_retrieval(x_src, y_src, x_tgt, y_tgt,
zeroshot=False, mixture=False):
mAP, prec = evaluate(x_tgt, y_tgt, x_src, y_src, mixture=mixture)
txt = ('mAP@all: %.04f Prec@100: %.04f\t' % (mAP, prec))
print(txt)
g_src_x = KNN(x_src, x_tgt, K=1, mode='ones')
if zeroshot:
alpha = 0.7
else:
alpha = 0.4
new_src_x = slerp(alpha, L2norm(x_src), L2norm(g_src_x))
mAP, prec = evaluate(x_tgt, y_tgt, new_src_x, y_src, mixture=mixture)
txt = ('mAP@all: %.04f Prec@100: %.04f\t' % (mAP, prec))
tmp = '(w. refinement)' % alpha
txt = tmp + ' ' + txt
print(txt)
return mAP
def evaluate(im_x, im_y, sk_x, sk_y, K=False, return_idx=False, mixture=False):
if not K:
idx = retrieve(sk_x, im_x)
else:
idx = myretrieve(sk_x, im_x, topK=K)
if mixture:
selection = np.load('plop.npy')
rows, cols = idx.shape
idx = idx[idx != selection[:, None]].reshape(rows, -1)
prec, mAP = score(sk_y, im_y, idx)
if return_idx:
return mAP, prec, idx
else:
return mAP, prec
def myretrieve(query, gallery, dist='euc', L2=True, topK=101):
d = query.shape[1]
if dist == 'euc':
index_flat = faiss.IndexFlatL2(d)
elif dist == 'cos':
index_flat = faiss.IndexFlatIP(d)
if L2:
query = L2norm(query)
gallery = L2norm(gallery)
index_flat.add(gallery)
D, I = index_flat.search(query, topK)
return I
def get_stats(splits):
domains = splits['domain'].unique()
categories = splits['cat'].unique()
stats = {}
for c in categories:
stats[c] = {}
total = 0.
for d in domains:
cond = np.logical_and(splits['domain'] == d, splits['cat'] == c)
stats[c][d] = np.sum(cond)
total += np.sum(cond)
for d in domains:
stats[c][d] /= total
return stats
def slerp(val, low, high):
"""Spherical interpolation. val has a range of 0 to 1."""
if val <= 0:
return low
elif val >= 1:
return high
elif np.allclose(low, high):
return low
omega = np.arccos(np.einsum('ij, ij->i', low, high))
so = np.sin(omega)
return (np.sin((1.0-val)*omega) / so)[:, None] * low + (np.sin(val*omega)/so)[:, None] * high
if __name__ == '__main__':
configs = get_config()
if args.eval == 'many2any':
many2any_retrieval(configs, sources=['quickdraw', 'quickdraw'])
many2any_retrieval(configs, sources=['quickdraw', 'infograph'])
many2any_retrieval(configs)
many2any_retrieval(configs, sources=['clipart', 'clipart'])
many2any_retrieval(configs, sources=['clipart', 'quickdraw'])
many2any_retrieval(configs, sources=['clipart', 'infograph'])
many2any_retrieval(configs, sources=['real', 'real'])
many2any_retrieval(configs, sources=['real', 'quickdraw'])
many2any_retrieval(configs, sources=['real', 'infograph'])
elif args.eval == 'any2many':
feats, labels, domains = get_data(configs)
splits = get_splits(configs)
one2many_retrieve_intent_aware(feats, labels, domains, splits)