forked from halwai/cnn-rnn-siamese-video-similarity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
eval.py.BASE.8280.py
139 lines (123 loc) · 5.87 KB
/
eval.py.BASE.8280.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
#KeyError: u'VariableV2'! /usr/bin/env python
from sklearn.metrics import precision_recall_curve
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
import os
import time
import datetime
#from tensorflow.contrib import learn
from eval_helper import InputHelper, compute_distance
from scipy import misc
# Parameters
# ==================================================
# Eval Parameters
tf.flags.DEFINE_integer("batch_size", 4, "Batch Size (default: 4)")
tf.flags.DEFINE_string("checkpoint_dir", "", "Checkpoint directory from training run")
tf.flags.DEFINE_string("model", "/home/tushar/codes/rnn-cnn/runs/1504859242/checkpoints/model-784", "Load trained model checkpoint (Default: None)")
tf.flags.DEFINE_string("eval_filepath", "/home/tushar/Heavy_dataset/gta_data/final/", "testing folder (default: /home/halwai/gta/final)")
tf.flags.DEFINE_string("ann_filepath", "./annotation_files/", "testing folde")
tf.flags.DEFINE_integer("max_frames", 20, "Maximum Number of frame (default: 20)")
tf.flags.DEFINE_string("loss", "contrastive", "Type of Loss functions:: contrastive/AAAI(default: contrastive)")
tf.flags.DEFINE_string("name","result" ,"name for saving" )
# Misc Parameters
tf.flags.DEFINE_boolean("allow_soft_placement", True, "Allow device soft device placement")
tf.flags.DEFINE_boolean("log_device_placement", False, "Log placement of ops on devices")
FLAGS = tf.flags.FLAGS
FLAGS._parse_flags()
print("\nParameters:")
for attr, value in sorted(FLAGS.__flags.items()):
print("{}={}".format(attr.upper(), value))
print("")
if FLAGS.eval_filepath==None or FLAGS.model==None :
print("Eval or Vocab filepaths are empty.")
exit()
# load data and map id-transform based on training time vocabulary
inpH = InputHelper()
x1_test,x2_test,y_test,video_lengths_test = inpH.getTestDataSet(FLAGS.ann_filepath, FLAGS.eval_filepath, FLAGS.max_frames)
print("\nEvaluating...\n")
# Evaluation
# ==================================================
checkpoint_file = FLAGS.model
print(checkpoint_file)
graph = tf.Graph()
with graph.as_default():
session_conf = tf.ConfigProto(
allow_soft_placement=FLAGS.allow_soft_placement,
log_device_placement=FLAGS.log_device_placement)
sess = tf.Session(config=session_conf)
with sess.as_default():
# Load the saved meta graph and restore variables
saver = tf.train.import_meta_graph("{}.meta".format(checkpoint_file))
sess.run(tf.global_variables_initializer())
saver.restore(sess, checkpoint_file)
# Get the placeholders from the graph by name
input_imgs = graph.get_operation_by_name("input_imgs").outputs[0]
input_x1 = graph.get_operation_by_name("input_x1").outputs[0]
input_x2 = graph.get_operation_by_name("input_x2").outputs[0]
input_y = graph.get_operation_by_name("input_y").outputs[0]
video_lengths = graph.get_operation_by_name("video_lengths").outputs[0]
dropout_keep_prob = graph.get_operation_by_name("dropout_keep_prob").outputs[0]
# Tensors we want to evaluate
conv_output = graph.get_operation_by_name("conv/output").outputs[0]
predictions = graph.get_tensor_by_name("distance:0")
print(conv_output, predictions)
# Generate batches for one epoch
batches = inpH.batch_iter(x1_test,x2_test,y_test,video_lengths_test, 1, 1, [[104, 114, 124], (227, 227)] ,shuffle=False, is_train=False)
# Collect the predictions here
all_predictions = []
all_dist=[]
all_labels=[]
sum_neg_correct=0.0
sum_pos_correct=0.0
for (x1_dev_b,x2_dev_b,y_dev_b,v_len_b) in batches:
misc.imsave('temp.png', np.vstack([np.hstack(x1_dev_b),np.hstack(x2_dev_b)]))
#print(x1_dev_b)
[x1] = sess.run([conv_output], {input_imgs: x1_dev_b})
[x2] = sess.run([conv_output], {input_imgs: x2_dev_b})
[dist] = sess.run([predictions], {input_x1: x1, input_x2: x2, input_y:y_dev_b, dropout_keep_prob: 1.0, video_lengths: v_len_b})
d = compute_distance(dist, FLAGS.loss)
correct = np.sum(y_dev_b==d)
print(dist, y_dev_b, d)
num_pos_correct=np.sum(d*correct)
num_neg_correct=np.sum(correct)-num_pos_correct
sum_pos_correct=sum_pos_correct+num_pos_correct
sum_neg_correct=sum_neg_correct+num_neg_correct
all_dist.append(dist)
all_predictions.append(correct)
all_labels.append(y_dev_b)
#for ex in all_predictions:
# print(ex)
correct_predictions = np.sum(all_predictions)*1.0/ len(all_predictions)
print("Accuracy: {:g} ".format(correct_predictions))
total_pos=np.sum(all_labels)
total_neg=(len(all_labels)-np.sum(all_labels))
positive_accuracy=sum_pos_correct*1.0/total_pos
negative_accuracy=sum_neg_correct*1.0/total_neg
print('total positives:')
print(total_pos)
print('positive accuracy')
print(positive_accuracy)
print('total negatives:')
print(total_neg)
print('negative accuracy')
print(negative_accuracy)
#invert dist also
dist2 = [1-x for x in all_dist]
precision, recall, _ = precision_recall_curve(all_labels,dist)
precision2,recall2,_=precision_recall_curve(all_labels,dist2)
plot_precision_recall(recall,precision,'0','./pr_0'+name)
plot_precision_recall(recall2,precision2,'1','./pr_1'+name)
"""
plplot(recall, precision, label=label)
#plt.step(recall, precision, color='b', alpha=0.2,
#where='post')
#plt.fill_between(recall, precision, step='post', alpha=0.2,
#color='b')
plt.xlabel('Recall')
plt.ylabel('Precision')
plt.ylim([0.0, 1.05])
plt.xlim([0.0, 1.0])
plt.title('2-class Precision-Recall curve')
plt.show()
"""