-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathlfw_eval.py
129 lines (103 loc) · 4.41 KB
/
lfw_eval.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
from PIL import Image
import numpy as np
from torchvision.transforms import functional as F
import torchvision.transforms as transforms
import torch
from torch.autograd import Variable
import torch.backends.cudnn as cudnn
cudnn.benchmark = True
import net
def extractDeepFeature(img, model, is_gray):
if is_gray:
transform = transforms.Compose([
transforms.Grayscale(),
transforms.ToTensor(), # range [0, 255] -> [0.0,1.0]
transforms.Normalize(mean=(0.5,), std=(0.5,)) # range [0.0, 1.0] -> [-1.0,1.0]
])
else:
transform = transforms.Compose([
transforms.ToTensor(), # range [0, 255] -> [0.0,1.0]
transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)) # range [0.0, 1.0] -> [-1.0,1.0]
])
'''
img, img_ = transform(img), transform(F.hflip(img))
img, img_ = img.unsqueeze(0).to('cuda'), img_.unsqueeze(0).to('cuda')
ft = torch.cat((model(img), model(img_)), 1)[0].to('cpu')
'''
img = transform(img)
img = img.unsqueeze(0).to('cuda')
ft = model(img)[0].to('cpu')
return ft
def KFold(n=6000, n_folds=10):
folds = []
base = list(range(n))
for i in range(n_folds):
test = base[int(i * n / n_folds):int((i + 1) * n / n_folds)]
train = list(set(base) - set(test))
folds.append([train, test])
return folds
def eval_acc(threshold, diff):
y_true = []
y_predict = []
for d in diff:
same = 1 if float(d[0]) > threshold else 0
y_predict.append(same)
y_true.append(int(d[1]))
y_true = np.array(y_true)
y_predict = np.array(y_predict)
accuracy = 1.0 * np.count_nonzero(y_true == y_predict) / len(y_true)
return accuracy
def find_best_threshold(thresholds, predicts):
best_threshold = best_acc = 0
for threshold in thresholds:
accuracy = eval_acc(threshold, predicts)
if accuracy >= best_acc:
best_acc = accuracy
best_threshold = threshold
return best_threshold
def eval(model, model_path=None, is_gray=False):
predicts = []
checkpoint = torch.load(model_path)
model.load_state_dict(checkpoint['model_state_dict'])
model.eval()
root = '/home/lingxuesong/data/lfw/lfw-112X96/'
with open('/home/lingxuesong/data/lfw/pairs.txt') as f:
pairs_lines = f.readlines()[1:]
with torch.no_grad():
for i in range(6000):
p = pairs_lines[i].replace('\n', '').split('\t')
if 3 == len(p):
sameflag = 1
name1 = p[0] + '/' + p[0] + '_' + '{:04}.jpg'.format(int(p[1]))
name2 = p[0] + '/' + p[0] + '_' + '{:04}.jpg'.format(int(p[2]))
elif 4 == len(p):
sameflag = 0
name1 = p[0] + '/' + p[0] + '_' + '{:04}.jpg'.format(int(p[1]))
name2 = p[2] + '/' + p[2] + '_' + '{:04}.jpg'.format(int(p[3]))
else:
raise ValueError("WRONG LINE IN 'pairs.txt! ")
with open(root + name1, 'rb') as f:
img1 = Image.open(f).convert('RGB')
with open(root + name2, 'rb') as f:
img2 = Image.open(f).convert('RGB')
f1 = extractDeepFeature(img1, model, is_gray)
f2 = extractDeepFeature(img2, model, is_gray)
distance = f1.dot(f2) / (f1.norm() * f2.norm() + 1e-5)
#predicts.append('{}\t{}\t{}\t{}\n'.format(name1, name2, distance, sameflag))
predicts.append([distance, sameflag])
accuracy = []
thd = []
folds = KFold(n=6000, n_folds=10)
thresholds = np.arange(-1.0, 1.0, 0.005)
#predicts = np.array(map(lambda line: line.strip('\n').split(), predicts))
predicts = np.array(predicts)
#print(type(predicts),predicts.shape,predicts[0])
for idx, (train, test) in enumerate(folds):
best_thresh = find_best_threshold(thresholds, predicts[train])
accuracy.append(eval_acc(best_thresh, predicts[test]))
thd.append(best_thresh)
print('LFWACC={:.4f} std={:.4f} thd={:.4f}'.format(np.mean(accuracy), np.std(accuracy), np.mean(thd)))
return np.mean(accuracy), predicts
if __name__ == '__main__':
_, result = eval(net.sphere().to('cuda'), model_path='checkpoint/CosFace_24_checkpoint.pth')
np.savetxt("result.txt", result, '%s')