forked from Kali-Hac/SGE-LA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
evaluate.py
289 lines (283 loc) · 10.4 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
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
import tensorflow as tf
from tensorflow.python.layers.core import Dense
import numpy as np
import time
import matplotlib as mpl
import copy
import os
# mpl.use('Agg')
# import matplotlib.pyplot as plt
import os
# Number of Epochs
epochs = 100
# Batch Size
batch_size = 128
# Time Steps of Input, f = 6 skeleton frames
time_steps = 6
# Length of Series, J = 20 body joints in a sequence
series_length = 20
# Learning Rate
learning_rate = 0.0005
dataset = False
attention = False
gpu = False
manner = False
tf.app.flags.DEFINE_string('attention', 'LA', "(LA) Locality-aware Attention or BA (Basic Attention)")
tf.app.flags.DEFINE_string('manner', 'ap', "sequence-level concatenation (sc) or average prediction (ap)")
tf.app.flags.DEFINE_string('dataset', 'BIWI', "Dataset: BIWI or IAS or KGBD")
tf.app.flags.DEFINE_string('gpu', '0', "GPU number")
FLAGS = tf.app.flags.FLAGS
def main(_):
global attention, dataset, series_length, epochs, time_steps, gpu, manner
attention, dataset, gpu, manner = FLAGS.attention, FLAGS.dataset, FLAGS.gpu, FLAGS.manner
if attention not in ['BA', 'LA']:
raise Exception('Attention must be BA or LA')
if manner not in ['sc', 'ap']:
raise Exception('Training manner must be sc or ap')
if dataset not in ['BIWI', 'IAS', 'KGBD']:
raise Exception('Dataset must be BIWI, IAS or KGBD')
if not gpu.isdigit() or int(gpu) < 0:
raise Exception('GPU number must be a positive integer')
os.environ['CUDA_VISIBLE_DEVICES'] = gpu
folder_name = dataset + '_' + attention
series_length=20
time_steps = 6
# epochs = 400
# print('Print the Validation Loss and Rank-1 Accuracy for each testing bacth: ')
evaluate_reid('./Models/AGEs_RN_models/' + dataset + '_' + attention + '_RN_' + manner)
def get_new_train_batches(targets, sources, batch_size):
if len(targets) < batch_size:
yield targets, sources
else:
for batch_i in range(0, len(sources) // batch_size):
start_i = batch_i * batch_size
sources_batch = sources[start_i:start_i + batch_size]
targets_batch = targets[start_i:start_i + batch_size]
yield targets_batch, sources_batch
def evaluate_reid(model_dir):
global batch_size, dataset, manner
X = np.load(model_dir + '/val_X.npy')
y = np.load(model_dir + '/val_y.npy')
if dataset == 'IAS':
X_2 = np.load(model_dir + '/val_2_X.npy')
y_2 = np.load(model_dir + '/val_2_y.npy')
if dataset == 'BIWI':
classes = [i for i in range(28)]
elif dataset == 'KGBD':
classes = [i for i in range(164)]
else:
classes = [i for i in range(11)]
checkpoint = model_dir + "/trained_model.ckpt"
loaded_graph = tf.get_default_graph()
from sklearn.preprocessing import label_binarize
from sklearn.metrics import roc_curve, auc
def cal_AUC(score_y, pred_y, ps, draw_pic=False):
score_y = np.array(score_y)
pred_y = label_binarize(np.array(pred_y), classes=classes)
# Compute micro-average ROC curve and ROC area
fpr, tpr, thresholds = roc_curve(pred_y.ravel(), score_y.ravel())
roc_auc = auc(fpr, tpr)
print(ps + ': ' + str(roc_auc))
if draw_pic:
fig = plt.figure()
lw = 2
plt.plot(fpr, tpr, color='darkorange',
lw=lw, label='ROC curve (area = %0.2f)' % roc_auc)
plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic: ' + ps)
plt.legend(loc="lower right")
fig.savefig('30 epoch ROC')
plt.close()
with tf.Session(graph=loaded_graph) as sess:
loader = tf.train.import_meta_graph(checkpoint + '.meta')
loader.restore(sess, checkpoint)
X_input = loaded_graph.get_tensor_by_name('X_input:0')
y_input = loaded_graph.get_tensor_by_name('y_input:0')
lr = loaded_graph.get_tensor_by_name('learning_rate:0')
pred = loaded_graph.get_tensor_by_name('add_1:0')
cost = loaded_graph.get_tensor_by_name('new_train/Mean:0')
accuracy = loaded_graph.get_tensor_by_name('new_train/Mean_1:0')
correct_num = 0
total_num = 0
rank_acc = {}
ys = []
preds = []
accs = []
cnt = 0
if dataset == 'IAS':
print('Validation Results on IAS-A: ')
if manner == 'sc':
for batch_i, (y_batch, X_batch) in enumerate(
get_new_train_batches(y, X, batch_size)):
loss, acc, pre = sess.run([cost, accuracy, pred],
{X_input: X_batch,
y_input: y_batch,
lr: learning_rate})
ys.extend(y_batch.tolist())
preds.extend(pre.tolist())
accs.append(acc)
cnt += 1
for i in range(y_batch.shape[0]):
for K in range(1, len(classes) + 1):
if K not in rank_acc.keys():
rank_acc[K] = 0
t = np.argpartition(pre[i], -K)[-K:]
if np.argmax(y_batch[i]) in t:
rank_acc[K] += 1
correct_num += acc * batch_size
total_num += batch_size
print(
'Testing Bacth: {:>3} - Validation Loss: {:>6.3f} - Validation Rank-1 Accuracy {:>6.3f}'
.format(cnt,
loss,
acc,
))
total_acc = correct_num / total_num
print('Rank-1 Accuracy: %f' % total_acc)
cal_AUC(score_y=preds,pred_y=ys, ps='nAUC')
else:
all_frame_preds = []
for batch_i, (y_batch, X_batch) in enumerate(
get_new_train_batches(y, X, batch_size)):
loss, acc, pre = sess.run([cost, accuracy, pred],
{X_input: X_batch,
y_input: y_batch,
lr: learning_rate})
ys.extend(y_batch.tolist())
preds.extend(pre.tolist())
all_frame_preds.extend(pre)
accs.append(acc)
cnt += 1
# for i in range(y_batch.shape[0]):
# for K in range(1, len(classes) + 1):
# if K not in rank_acc.keys():
# rank_acc[K] = 0
# t = np.argpartition(pre[i], -K)[-K:]
# if np.argmax(y_batch[i]) in t:
# rank_acc[K] += 1
# correct_num += acc * batch_size
# total_num += batch_size
# print(
# 'Testing Bacth: {:>3} - Validation Loss: {:>6.3f} - Validation Rank-1 Accuracy {:>6.3f}'
# .format(cnt,
# loss,
# acc,
# ))
sequence_pred_correct = 0
sequence_num = 0
sequence_preds = []
sequence_ys = []
for k in range(len(all_frame_preds) // time_steps):
sequence_labels = np.argmax(y[k * time_steps: (k + 1) * time_steps], axis=1)
# print(sequence_labels)
if (sequence_labels == np.tile(sequence_labels[0], [sequence_labels.shape[0]])).all():
frame_predictions = np.array(all_frame_preds[k * time_steps: (k + 1) * time_steps])
sequence_pred = np.argmax(np.average(frame_predictions, axis=0))
if sequence_pred == sequence_labels[0]:
sequence_pred_correct += 1
sequence_num += 1
sequence_ys.append(sequence_labels[0])
aver = np.average(frame_predictions, axis=0)
sequence_preds.append(aver)
seq_acc_t = sequence_pred_correct / sequence_num
# total_acc = correct_num / total_num
# print('(Frame) Rank-1 Accuracy: %f' % total_acc)
print('Rank-1 Accuracy: %f' % seq_acc_t)
sequence_ys = label_binarize(sequence_ys, classes=classes)
# cal_AUC(score_y=preds,pred_y=ys, ps='nAUC')
cal_AUC(score_y=sequence_preds, pred_y=sequence_ys, ps='nAUC')
if dataset == 'IAS':
print('Validation Results on IAS-B: ')
# IAS-B
if manner == 'sc':
correct_num = 0
total_num = 0
rank_acc = {}
ys = []
preds = []
accs = []
cnt = 0
for batch_i, (y_batch, X_batch) in enumerate(
get_new_train_batches(y_2, X_2, batch_size)):
loss, acc, pre = sess.run([cost, accuracy, pred],
{X_input: X_batch,
y_input: y_batch,
lr: learning_rate})
ys.extend(y_batch.tolist())
preds.extend(pre.tolist())
accs.append(acc)
cnt += 1
# for i in range(y_batch.shape[0]):
# for K in range(1, len(classes) + 1):
# if K not in rank_acc.keys():
# rank_acc[K] = 0
# t = np.argpartition(pre[i], -K)[-K:]
# if np.argmax(y_batch[i]) in t:
# rank_acc[K] += 1
# correct_num += acc * batch_size
# total_num += batch_size
# print(
# 'Testing Bacth: {:>3} - Validation Loss: {:>6.3f} - Validation Rank-1 Accuracy {:>6.3f}'
# .format(cnt,
# loss,
# acc,
# ))
# total_acc = correct_num / total_num
print('Rank-1 Accuracy: %f' % total_acc)
cal_AUC(score_y=preds, pred_y=ys, ps='nAUC')
else:
all_frame_preds = []
for batch_i, (y_batch, X_batch) in enumerate(
get_new_train_batches(y_2, X_2, batch_size)):
loss, acc, pre = sess.run([cost, accuracy, pred],
{X_input: X_batch,
y_input: y_batch,
lr: learning_rate})
ys.extend(y_batch.tolist())
preds.extend(pre.tolist())
accs.append(acc)
all_frame_preds.extend(pre)
cnt += 1
# for i in range(y_batch.shape[0]):
# for K in range(1, len(classes) + 1):
# if K not in rank_acc.keys():
# rank_acc[K] = 0
# t = np.argpartition(pre[i], -K)[-K:]
# if np.argmax(y_batch[i]) in t:
# rank_acc[K] += 1
# correct_num += acc * batch_size
# total_num += batch_size
# print(
# 'Testing Bacth: {:>3} - Validation Loss: {:>6.3f} - Validation Rank-1 Accuracy {:>6.3f}'
# .format(cnt,
# loss,
# acc,
# ))
sequence_pred_correct = 0
sequence_num = 0
sequence_preds = []
sequence_ys = []
for k in range(len(all_frame_preds) // time_steps):
sequence_labels = np.argmax(y_2[k * time_steps: (k + 1) * time_steps], axis=1)
if (sequence_labels == np.tile(sequence_labels[0], [sequence_labels.shape[0]])).all():
frame_predictions = np.array(all_frame_preds[k * time_steps: (k + 1) * time_steps])
sequence_pred = np.argmax(np.average(frame_predictions, axis=0))
if sequence_pred == sequence_labels[0]:
sequence_pred_correct += 1
sequence_num += 1
sequence_ys.append(sequence_labels[0])
aver = np.average(frame_predictions, axis=0)
sequence_preds.append(aver)
seq_acc_t = sequence_pred_correct / sequence_num
# total_acc = correct_num / total_num
# print('(Frame) Rank-1 Accuracy: %f' % total_acc)
print('Rank-1 Accuracy: %f' % seq_acc_t)
sequence_ys = label_binarize(sequence_ys, classes=classes)
# cal_AUC(score_y=preds, pred_y=ys, ps='nAUC')
cal_AUC(score_y=sequence_preds, pred_y=sequence_ys, ps='nAUC')
if __name__ == '__main__':
tf.app.run()