-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathevaluation.py
276 lines (242 loc) · 10.7 KB
/
evaluation.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
import numpy as np
import pickle
import cv2
import tensorflow as tf
import mxnet as mx
import datetime
import sklearn
from sklearn.model_selection import KFold
from sklearn.decomposition import PCA
from scipy import interpolate
from resnet import ResNet50, train_model
def calculate_roc(thresholds, embeddings1, embeddings2, actual_issame, nrof_folds=10, pca=0):
assert (embeddings1.shape[0] == embeddings2.shape[0])
assert (embeddings1.shape[1] == embeddings2.shape[1])
nrof_pairs = min(len(actual_issame), embeddings1.shape[0])
nrof_thresholds = len(thresholds)
k_fold = KFold(n_splits=nrof_folds, shuffle=False)
tprs = np.zeros((nrof_folds, nrof_thresholds))
fprs = np.zeros((nrof_folds, nrof_thresholds))
accuracy = np.zeros((nrof_folds))
indices = np.arange(nrof_pairs)
# print('pca', pca)
if pca == 0:
diff = np.subtract(embeddings1, embeddings2)
dist = np.sum(np.square(diff), 1)
# for i in range(len(dist)):
# dist[i] = abs(np.dot(embeddings1[i], embeddings2[i]))
for fold_idx, (train_set, test_set) in enumerate(k_fold.split(indices)):
# print('train_set', train_set)
# print('test_set', test_set)
if pca > 0:
print('doing pca on', fold_idx)
embed1_train = embeddings1[train_set]
embed2_train = embeddings2[train_set]
_embed_train = np.concatenate((embed1_train, embed2_train), axis=0)
# print(_embed_train.shape)
pca_model = PCA(n_components=pca)
pca_model.fit(_embed_train)
embed1 = pca_model.transform(embeddings1)
embed2 = pca_model.transform(embeddings2)
embed1 = sklearn.preprocessing.normalize(embed1)
embed2 = sklearn.preprocessing.normalize(embed2)
# print(embed1.shape, embed2.shape)
diff = np.subtract(embed1, embed2)
dist = np.sum(np.square(diff), 1)
# for i in range(len(dist)):
# dist[i] = abs(np.dot(embed1[i], embed1[i]))
# Find the best threshold for the fold
acc_train = np.zeros((nrof_thresholds))
for threshold_idx, threshold in enumerate(thresholds):
_, _, acc_train[threshold_idx] = calculate_accuracy(
threshold, dist[train_set], actual_issame[train_set])
best_threshold_index = np.argmax(acc_train)
print('best_threshold_index', best_threshold_index,
acc_train[best_threshold_index])
for threshold_idx, threshold in enumerate(thresholds):
tprs[fold_idx, threshold_idx], fprs[fold_idx, threshold_idx], _ = calculate_accuracy(threshold,
dist[test_set],
actual_issame[
test_set])
_, _, accuracy[fold_idx] = calculate_accuracy(thresholds[best_threshold_index], dist[test_set],
actual_issame[test_set])
tpr = np.mean(tprs, 0)
fpr = np.mean(fprs, 0)
return tpr, fpr, accuracy
def calculate_accuracy(threshold, dist, actual_issame):
predict_issame = np.less(dist, threshold)
# predict_issame = np.less(threshold, dist)
tp = np.sum(np.logical_and(predict_issame, actual_issame))
fp = np.sum(np.logical_and(predict_issame, np.logical_not(actual_issame)))
tn = np.sum(np.logical_and(np.logical_not(
predict_issame), np.logical_not(actual_issame)))
fn = np.sum(np.logical_and(np.logical_not(predict_issame), actual_issame))
tpr = 0 if (tp + fn == 0) else float(tp) / float(tp + fn)
fpr = 0 if (fp + tn == 0) else float(fp) / float(fp + tn)
acc = float(tp + tn) / dist.size
return tpr, fpr, acc
def calculate_val(thresholds, embeddings1, embeddings2, actual_issame, far_target, nrof_folds=10):
'''
Copy from [insightface](https://github.com/deepinsight/insightface)
:param thresholds:
:param embeddings1:
:param embeddings2:
:param actual_issame:
:param far_target:
:param nrof_folds:
:return:
'''
assert (embeddings1.shape[0] == embeddings2.shape[0])
assert (embeddings1.shape[1] == embeddings2.shape[1])
nrof_pairs = min(len(actual_issame), embeddings1.shape[0])
nrof_thresholds = len(thresholds)
k_fold = KFold(n_splits=nrof_folds, shuffle=False)
val = np.zeros(nrof_folds)
far = np.zeros(nrof_folds)
diff = np.subtract(embeddings1, embeddings2)
dist = np.sum(np.square(diff), 1)
indices = np.arange(nrof_pairs)
for fold_idx, (train_set, test_set) in enumerate(k_fold.split(indices)):
# Find the threshold that gives FAR = far_target
far_train = np.zeros(nrof_thresholds)
for threshold_idx, threshold in enumerate(thresholds):
_, far_train[threshold_idx] = calculate_val_far(
threshold, dist[train_set], actual_issame[train_set])
if np.max(far_train) >= far_target:
f = interpolate.interp1d(far_train, thresholds, kind='slinear')
threshold = f(far_target)
else:
threshold = 0.0
val[fold_idx], far[fold_idx] = calculate_val_far(
threshold, dist[test_set], actual_issame[test_set])
val_mean = np.mean(val)
far_mean = np.mean(far)
val_std = np.std(val)
return val_mean, val_std, far_mean
def calculate_val_far(threshold, dist, actual_issame):
predict_issame = np.less(dist, threshold)
true_accept = np.sum(np.logical_and(predict_issame, actual_issame))
false_accept = np.sum(np.logical_and(
predict_issame, np.logical_not(actual_issame)))
n_same = np.sum(actual_issame)
n_diff = np.sum(np.logical_not(actual_issame))
val = float(true_accept) / float(n_same)
far = float(false_accept) / float(n_diff)
return val, far
def evaluate(embeddings, actual_issame, nrof_folds=10, pca=0):
# Calculate evaluation metrics
thresholds = np.arange(0, 4, 0.01)
embeddings1 = embeddings[0::2]
embeddings2 = embeddings[1::2]
tpr, fpr, accuracy = calculate_roc(thresholds, embeddings1, embeddings2,
np.asarray(actual_issame), nrof_folds=nrof_folds, pca=pca)
thresholds = np.arange(0, 4, 0.001)
val, val_std, far = calculate_val(thresholds, embeddings1, embeddings2,
np.asarray(actual_issame), 1e-3, nrof_folds=nrof_folds)
return tpr, fpr, accuracy, val, val_std, far
def load_bin(path, image_size):
bins, issame_list = pickle.load(
open(path, 'rb'), encoding='bytes')
data_list = []
for _ in [0, 1]:
data = np.empty(
(len(issame_list) * 2, image_size[0], image_size[1], 3))
data_list.append(data)
for i in range(len(issame_list) * 2):
_bin = bins[i]
img = mx.image.imdecode(_bin).asnumpy()
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
for flip in [0, 1]:
if flip == 1:
img = np.fliplr(img)
data_list[flip][i, ...] = img
i += 1
if i % 1000 == 0:
print('loading bin', i)
print(data_list[0].shape)
return data_list, issame_list
def data_iter(datasets, batch_size):
data_num = datasets.shape[0]
for i in range(0, data_num, batch_size):
yield datasets[i:min(i + batch_size, data_num), ...]
def test(data_set, batch_size, model):
'''
referenc official implementation [insightface](https://github.com/deepinsight/insightface)
:param data_set:
:param batch_size:
:param model:
:return:
'''
data_list = data_set[0]
issame_list = data_set[1]
embeddings_list = []
time_consumed = 0.0
for i in range(len(data_list)):
datas = data_list[i]
embeddings = None
for idx, data in enumerate(data_iter(datas, batch_size)):
data_tmp = data.copy() # fix issues #4
data_tmp -= 127.5
data_tmp *= 0.0078125
data_tmp = tf.cast(data_tmp, tf.float32)
time0 = datetime.datetime.now()
_embeddings = model(data_tmp)
time_now = datetime.datetime.now()
diff = time_now - time0
time_consumed += diff.total_seconds()
if embeddings is None:
embeddings = np.zeros((datas.shape[0], _embeddings.shape[1]))
try:
embeddings[idx * batch_size:min((idx + 1) *
batch_size, datas.shape[0]), ...] = _embeddings
except ValueError:
print('idx*batch_size value is %d min((idx+1)*batch_size, datas.shape[0]) %d, batch_size %d, data.shape[0] %d' %
(idx * batch_size, min((idx + 1) * batch_size, datas.shape[0]), batch_size, datas.shape[0]))
print('embedding shape is ', _embeddings.shape)
embeddings_list.append(embeddings)
_xnorm = 0.0
_xnorm_cnt = 0
for embed in embeddings_list:
for i in range(embed.shape[0]):
_em = embed[i]
_norm = np.linalg.norm(_em)
# print(_em.shape, _norm)
_xnorm += _norm
_xnorm_cnt += 1
_xnorm /= _xnorm_cnt
acc1 = 0.0
std1 = 0.0
embeddings = embeddings_list[0] + embeddings_list[1]
embeddings = sklearn.preprocessing.normalize(embeddings)
print(embeddings.shape)
print('infer time', time_consumed)
_, _, accuracy, val, val_std, far = evaluate(
embeddings, issame_list, nrof_folds=10)
acc2, std2 = np.mean(accuracy), np.std(accuracy)
return acc1, std1, acc2, std2, _xnorm
def ver_test(data_set, dataset_name, batch_size, model):
for i in range(len(dataset_name)):
print('testing %s..' % (dataset_name[i]))
acc1, std1, acc2, std2, xnorm = test(data_set=data_set[i],
batch_size=batch_size,
model=model)
print('[%s]XNorm: %f' % (dataset_name[i], xnorm))
print('[%s]Accuracy: %1.5f+-%1.5f' % (dataset_name[i], acc2, std2))
tmodel = train_model()
dataset = []
dataset_name = []
dataset.append(load_bin('dataset/faces_webface_112x112/lfw.bin', [112, 112]))
dataset_name.append('lfw')
dataset.append(
load_bin('dataset/faces_webface_112x112/cfp_ff.bin', [112, 112]))
dataset_name.append('cfp_ff')
dataset.append(
load_bin('dataset/faces_webface_112x112/cfp_fp.bin', [112, 112]))
dataset_name.append('cfp_fp')
dataset.append(
load_bin('dataset/faces_webface_112x112/agedb_30.bin', [112, 112]))
dataset_name.append('agedb_30')
for i in [52000]:
tmodel.load_weights('output/ckpt/weights_step-%d' % i)
model = tmodel.resnet
ver_test(dataset, dataset_name, 16, model)