forked from rish-16/cs4243-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
engine.py
239 lines (185 loc) · 8.87 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
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
import numpy as np
import torch
import torch.nn.functional as F
from torchvision import transforms
from model_training import *
class Engine(object):
"""
The search engine that maintains a database and retrieve the real images that
are the most similar to the input doodle.
The only optimization is the cuda acceleration.
Higher speedup can be achieved via batch preprocessing of the database.
"""
def __init__(self, dataset, doodle_model, real_model):
self.doodle_model = doodle_model
self.real_model = real_model
self.doodle_model.eval()
self.real_model.eval()
self.database = self.get_database_from_dataset(dataset) # format: {vec: (img, label)}
print(f'Engine ready. Database size: {len(self.database)}')
def query(self, doodle_img, topk=1):
doodle_img = doodle_img.reshape(64, 64, 1)
def get_doodle_transforms(X, size):
T = transforms.Compose([
transforms.ToPILImage(),
transforms.Resize(size),
transforms.ToTensor(),
transforms.Normalize((X/255).mean(axis=(0, 1, 2)),
(X/255).std(axis=(0, 1, 2)))])
return T
doodle_preprocess = get_doodle_transforms(doodle_img, 64)
doodle_img = doodle_preprocess(doodle_img).unsqueeze(0)
print (doodle_img.shape, type(doodle_img), doodle_img.dtype)
with torch.no_grad():
_, query_vector = self.doodle_model(doodle_img, return_feats=True)
sims, retrieved_samples = [], []
for vec_db, (img_db, label_db) in self.database.items():
sims.append(F.cosine_similarity(query_vector, vec_db, dim=1).item())
retrieved_samples.append((img_db, label_db))
topk_id = np.argpartition(sims, len(sims) - topk)[-topk:]
return [retrieved_samples[x][0] for x in topk_id] # only return the image
def get_database_from_dataset(self, dataset):
# take a dataset object as input
def get_real_transforms(X, size):
T = transforms.Compose([
transforms.ToPILImage(),
transforms.Resize(size),
transforms.ToTensor(),
transforms.Normalize((X/255).mean(), (X/255).std())])
return T
real_data, real_label = dataset.X, dataset.Y # np arrays
real_preprocess = get_real_transforms(real_data, 64)
pairs = {}
for i, (data, label) in enumerate(zip(real_data, real_label)):
data_processed = real_preprocess(data)
with torch.no_grad():
# here we use a batch size of 1.
# A larger value can lead to speedup, but it requires some engineering
_, vec = self.real_model(data_processed.unsqueeze(0), return_feats=True)
img_label_pair = (data, label)
pairs[vec] = img_label_pair
if i % 1000 == 0:
print(f'building database... [{i} / {len(real_data)}]')
return pairs
class Engine2(object):
"""
The search engine that maintains a database and retrieve the real images that
are the most similar to the input doodle.
The only optimization is the cuda acceleration.
Higher speedup can be achieved via batch preprocessing of the database.
"""
def __init__(self, dataset):
self.doodle_model.eval()
self.real_model.eval()
self.database = self.get_database_from_dataset(dataset) # format: {vec: (img, label)}
print(f'Engine ready. Database size: {len(self.database)}')
def query(self, doodle_img, doodle_model, topk=1):
doodle_img = doodle_img.reshape(64, 64, 1)
print ("shape: ", doodle_img.shape)
def get_doodle_transforms(X, size):
T = transforms.Compose([
transforms.ToPILImage(),
transforms.Resize(size),
transforms.ToTensor(),
transforms.Normalize((X/255).mean(axis=(0, 1, 2)),
(X/255).std(axis=(0, 1, 2)))])
return T
doodle_preprocess = get_doodle_transforms(doodle_img, 64)
doodle_img = doodle_preprocess(doodle_img).unsqueeze(0)
with torch.no_grad():
_, query_vector = doodle_model(doodle_img, return_feats=True)
sims, retrieved_samples = [], []
for vec_db, (img_db, label_db) in self.database.items():
sims.append(F.cosine_similarity(query_vector, vec_db, dim=1).item())
retrieved_samples.append((img_db, label_db))
topk_id = np.argpartition(sims, len(sims) - topk)[-topk:]
return [retrieved_samples[x][0] for x in topk_id] # only return the image
def get_database_from_dataset(self, real_model, dataset):
# take a dataset object as input
def get_real_transforms(X, size):
T = transforms.Compose([
transforms.ToPILImage(),
transforms.Resize(size),
transforms.ToTensor(),
transforms.Normalize((X/255).mean(), (X/255).std())])
return T
real_data, real_label = dataset.X, dataset.Y # np arrays
real_preprocess = get_real_transforms(real_data, 64)
pairs = {}
for i, (data, label) in enumerate(zip(real_data, real_label)):
data_processed = real_preprocess(data)
with torch.no_grad():
# here we use a batch size of 1.
# A larger value can lead to speedup, but it requires some engineering
_, vec = real_model(data_processed.unsqueeze(0), return_feats=True)
img_label_pair = (data, label)
pairs[vec] = img_label_pair
if i % 1000 == 0:
print(f'building database... [{i} / {len(real_data)}]')
return pairs
class Engine3(object):
"""
The search engine that maintains a database and retrieve the real images that
are the most similar to the input doodle.
The only optimization is the cuda acceleration.
Higher speedup can be achieved via batch preprocessing of the database.
"""
def __init__(self, dataset, doodle_model, real_model):
self.doodle_model = doodle_model
self.real_model = real_model
self.doodle_model.eval()
self.real_model.eval()
self.database = self.get_database_from_dataset(dataset) # format: {vec: (img, label)}
# print(f'Engine ready. Database size: {len(self.database)}')
def query(self, doodle_img, topk=1):
doodle_img = torch.from_numpy(doodle_img).view(1, 64, 64).float().unsqueeze(0)
with torch.no_grad():
_, query_vector = self.doodle_model(doodle_img, return_feat=True)
sims, retrieved_samples = [], []
for vec_db, (img_db, label_db) in self.database.items():
sims.append(F.cosine_similarity(query_vector, vec_db, dim=1).item())
retrieved_samples.append((img_db, label_db))
topk_id = np.argpartition(sims, len(sims) - topk)[-topk:]
return [retrieved_samples[x] for x in topk_id]
def get_database_from_dataset(self, dataset):
# take a dataset object as input
def get_real_transforms(X, size):
T = transforms.Compose([
transforms.ToPILImage(),
transforms.Resize(size),
transforms.ToTensor(),
transforms.Normalize((X / 255).mean(), (X / 255).std())])
return T
real_data, real_label = dataset.X, dataset.Y # np arrays
real_preprocess = get_real_transforms(real_data, 64)
pairs = {}
for i, (data, label) in enumerate(zip(real_data, real_label)):
data_processed = real_preprocess(data)
with torch.no_grad():
# here we use a batch size of 1.
# A larger value can lead to speedup, but it requires some engineering
_, vec = self.real_model(data_processed.unsqueeze(0), return_feat=True)
img_label_pair = (data, label)
pairs[vec] = img_label_pair
# if i % 1000 == 0:
# print(f'building database... [{i} / {len(real_data)}]')
return pairs
def test_search_acc_top(doodle_model, real_model, engine, doodle_val_set, n=100, k=5, verbose=False):
"""
n is the number of queries
k is the top-k value for the engine
verbose = True will show the testing progress
"""
accs = []
for i in range(n):
idx = random.randint(0, len(doodle_val_set) - 1) # sample a random index
doodle, doodle_label = doodle_val_set[i] # a random doodle sample
out_samples = engine.query(doodle.numpy(), topk=k)
pred_labels = [x[1] for x in out_samples]
if doodle_label in pred_labels:
accs.append(1)
else:
accs.append(0)
if i % 10 == 0 and verbose:
print(i, n)
return sum(accs)/len(accs)