-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathtest_memory.py
172 lines (140 loc) · 6.21 KB
/
test_memory.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
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import _init_paths
import os
import sys
import time
import cv2
import torch
from torch.autograd import Variable
from torch.utils.data.sampler import Sampler
from data_preprocess import ADE
from batchLoader import BatchLoader
from model import vgg16, res50, memory_res50
from opts import parse_args
from visualization import *
try:
import tensorflow as tf
except ImportError:
print("Tensorflow not installed; No tensorboard logging.")
tf = None
def add_summary_value(writer, key, value, iteration):
summary = tf.Summary(value=[tf.Summary.Value(tag=key, simple_value=value)])
writer.add_summary(summary, iteration)
def check_rootfolders(trainid):
"""Create log and model folder"""
folders_util = [args.root_log, args.root_model, args.root_output]
if not os.path.exists('./data/results'):
os.makedirs('./data/results')
for folder in folders_util:
if not os.path.exists(os.path.join('./data/results', trainid, folder)):
print('creating folder ' + folder)
os.makedirs(os.path.join('./data/results', trainid, folder))
if __name__ == '__main__':
args = parse_args()
if args.batch_size != 1:
print('The batch size should always be 1 for now.')
raise NotImplementedError
check_rootfolders(args.train_id)
summary_w = tf and tf.summary.FileWriter(\
os.path.join('./data/results', args.train_id, args.root_log)) # tensorboard
print('Called with args:')
print(args)
np.random.seed(args.RNG_SEED)
torch.backends.cudnn.enabled = False
if torch.cuda.is_available() and not args.cuda:
print("WARNING: You have a CUDA device, \
so you should probably run with --cuda")
pd_test = ADE('mtest', args) # without flipper append
args.CLASSES = pd_test.classes
print('{:d} test roidb entries'.format(len(pd_test.roidb)))
pd_test.filter_roidb()
test_size = len(pd_test.roidb)
dataloader = torch.utils.data.DataLoader(BatchLoader(pd_test.roidb, args, phase='test'), batch_size=1, \
num_workers=args.num_workers, shuffle=False)
# initilize the tensor holder here.
im_data = torch.FloatTensor(1)
im_info = torch.FloatTensor(1)
num_boxes = torch.LongTensor(1)
gt_boxes = torch.FloatTensor(1)
memory_size = torch.FloatTensor(1)
# ship to cuda
if args.cuda:
im_data = im_data.cuda()
im_info = im_info.cuda()
num_boxes = num_boxes.cuda()
gt_boxes = gt_boxes.cuda()
memory_size = memory_size.cuda()
# make variable
im_data = Variable(im_data)
im_info = Variable(im_info)
num_boxes = Variable(num_boxes)
gt_boxes = Variable(gt_boxes)
memory_size = Variable(memory_size)
if args.cuda:
args.CUDA = True
# initilize the network here.
if args.net == 'vgg16':
basenet = vgg16(pd_test.classes, args, pretrained=True)
elif args.net == 'res50':
basenet = res50(pd_test.classes, args, pretrained=True)
elif args.net == 'memory_res50':
basenet = memory_res50(pd_test.classes, args, pretrained=True)
else:
print("network is not defined")
basenet.create_architecture()
load_name = os.path.join('./data/results', args.train_id, 'model', args.model_name)
print("loading checkpoint %s" % load_name)
checkpoint = torch.load(load_name)
basenet.load_state_dict(checkpoint['model'])
print("loaded checkpoint %s" % load_name)
if args.cuda:
basenet.cuda()
iters_per_epoch = int(test_size / args.batch_size)
total_iters = 1
total_time = 0.
# eval model every epoch
data_iter_val = iter(dataloader)
basenet.eval()
loss_tt = 0.
start = time.time()
all_scores = [[] for _ in range(len(pd_test.roidb))]
for step in range(len(pd_test.roidb)):
data = next(data_iter_val)
im_data.data.resize_(data[0].size()).copy_(data[0])
im_info.data.resize_(data[1].size()).copy_(data[1])
gt_boxes.data.resize_(data[2].size()).copy_(data[2])
memory_size.data.resize_(data[3].size()).copy_(data[3])
cls_prob, cls_loss, cross_entropy_image, cross_entropy_memory, ce_final = basenet(im_data, im_info, gt_boxes, memory_size)
all_scores[step] = cls_prob.data.cpu().numpy()
loss = cls_loss.mean()
loss_tt += loss.data[0]
if True and step % 10 == 0:
basename = os.path.basename(pd_test.image_path_at(step)).split('.')[0]
im_vis, wrong = draw_predicted_boxes_test(data[4].cpu().numpy()[0], all_scores[step], data[5].cpu().numpy()[0], args)
if not os.path.exists(os.path.join('./data/images', args.train_id)):
os.makedirs(os.path.join('./data/images', args.train_id))
out_image = os.path.join('./data/images', args.train_id, basename + '.jpg')
cv2.imwrite(out_image, im_vis)
if step % args.disp_interval == 0:
end = time.time()
total_time += end - start
loss_rcnn_cls = cls_loss.data[0]
sys.stdout.write(
"evaling: [iter %4d/%4d] ; time cost: %f; rcnn_cls: %.4f\r" % (
step, len(pd_test.roidb), end - start, loss_rcnn_cls))
start = time.time()
sys.stdout.flush()
res_file = os.path.join('./data/results', args.train_id, args.root_output, 'all_scores.pkl')
import cPickle as pickle
with open(res_file, 'wb') as f:
pickle.dump(all_scores, f, pickle.HIGHEST_PROTOCOL)
print('all_scores saved!')
print('Evaluating detections')
mcls_sc, mcls_ac, mcls_ap, mins_sc, mins_ac, mins_ap = pd_test.evaluate(all_scores)
eval_file = os.path.join('./data/results', args.train_id, args.root_output, 'results.txt')
with open(eval_file, 'w') as f:
f.write('{:.3f} {:.3f} {:.3f} {:.3f}'.format(mins_ap, mins_ac, mcls_ap, mcls_ac))
print('total time: %.2f s, %.2f h' % (total_time, total_time / 3600.))
print('each iter time: %.2f s' % (total_time / float(len(pd_test.roidb))))