-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest.py
executable file
·181 lines (154 loc) · 6.49 KB
/
test.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
# test.py
import time
import torch
from torch.autograd import Variable
import plugins
class Tester:
def __init__(self, args, model, criterion, evaluation):
self.args = args
self.model = model
self.criterion = criterion
self.evaluation = evaluation
self.save_results = args.save_results
self.env = args.env
self.port = args.port
self.dir_save = args.save_dir
self.log_type = args.log_type
self.cuda = args.cuda
self.nepochs = args.nepochs
self.batch_size = args.batch_size
self.resolution_high = args.resolution_high
self.resolution_wide = args.resolution_wide
# for classification
self.labels = torch.zeros(self.batch_size).long()
self.inputs = torch.zeros(
self.batch_size,
self.resolution_high,
self.resolution_wide
)
if args.cuda:
self.labels = self.labels.cuda()
self.inputs = self.inputs.cuda()
self.inputs = Variable(self.inputs, volatile=True)
self.labels = Variable(self.labels, volatile=True)
# logging testing
self.log_loss = plugins.Logger(
args.logs_dir,
'TestLogger.txt',
self.save_results
)
self.params_loss = ['Loss', 'Accuracy']
self.log_loss.register(self.params_loss)
# monitor testing
self.monitor = plugins.Monitor(smoothing=True)
self.params_monitor = {
'Loss': {'dtype': 'running_mean'},
'Accuracy': {'dtype': 'running_mean'}
}
self.monitor.register(self.params_monitor)
# visualize testing
self.visualizer = plugins.Visualizer(self.port, self.env, 'Test')
self.params_visualizer = {
'Loss': {'dtype': 'scalar', 'vtype': 'plot', 'win': 'loss',
'layout': {'windows': ['train', 'test'], 'id': 1}},
'Accuracy': {'dtype': 'scalar', 'vtype': 'plot', 'win': 'accuracy',
'layout': {'windows': ['train', 'test'], 'id': 1}},
'Test_Image': {'dtype': 'image', 'vtype': 'image',
'win': 'test_image'},
'Test_Images': {'dtype': 'images', 'vtype': 'images',
'win': 'test_images'},
}
self.visualizer.register(self.params_visualizer)
if self.log_type == 'traditional':
# display training progress
self.print_formatter = 'Test [%d/%d][%d/%d] '
for item in self.params_loss:
self.print_formatter += item + " %.4f "
elif self.log_type == 'progressbar':
# progress bar message formatter
self.print_formatter = '({}/{})' \
' Load: {:.6f}s' \
' | Process: {:.3f}s' \
' | Total: {:}' \
' | ETA: {:}'
for item in self.params_loss:
self.print_formatter += ' | ' + item + ' {:.4f}'
self.evalmodules = []
self.losses = {}
def model_eval(self):
self.model.eval()
def test(self, epoch, dataloader):
dataloader = dataloader['test']
self.monitor.reset()
torch.cuda.empty_cache()
# switch to eval mode
self.model_eval()
if self.log_type == 'progressbar':
# progress bar
processed_data_len = 0
bar = plugins.Bar('{:<10}'.format('Test'), max=len(dataloader))
end = time.time()
correct = 0
test_loss = 0
incorrect = []
inc_pred = []
actual_ans = []
inc_inputs = []
for i, (inputs, labels) in enumerate(dataloader):
# keeps track of data loading time
data_time = time.time() - end
############################
# Evaluate Network
############################
batch_size = inputs.size(0)
self.inputs.data.resize_(inputs.size()).copy_(inputs)
self.labels.data.resize_(labels.size()).copy_(labels)
self.model.zero_grad()
output = self.model(self.inputs)
loss = self.criterion(output, self.labels)
test_loss += loss.data[0]
acc = self.evaluation(output, self.labels)
pred = output.data.max(1, keepdim=True)[1]
correct += pred.eq(self.labels.data.view_as(pred)).long().cpu().sum()
inc = pred.ne(self.labels.data.view_as(pred)).squeeze().nonzero().squeeze().long()
if inc.numel() > 0:
inc_inputs.append(inputs[inc.tolist()])
inc_pred.extend(pred[inc].cpu().squeeze().tolist())
actual_ans.extend(self.labels.data[inc].cpu().squeeze().tolist())
incorrect.extend(inc.cpu().add_(i*len(dataloader)).squeeze().tolist())
self.losses['Accuracy'] = acc
self.losses['Loss'] = loss.data[0]
self.monitor.update(self.losses, batch_size)
if self.log_type == 'traditional':
# print batch progress
print(self.print_formatter % tuple(
[epoch + 1, self.nepochs, i, len(dataloader)] +
[self.losses[key] for key in self.params_monitor]))
elif self.log_type == 'progressbar':
# update progress bar
batch_time = time.time() - end
processed_data_len += len(inputs)
bar.suffix = self.print_formatter.format(
*[processed_data_len, len(dataloader.sampler), data_time,
batch_time, bar.elapsed_td, bar.eta_td] +
[self.losses[key] for key in self.params_monitor]
)
bar.next()
end = time.time()
if self.log_type == 'progressbar':
bar.finish()
print(incorrect)
print("Correct ", actual_ans)
print("Predict ", inc_pred)
test_loss /= len(dataloader.dataset)
print('\nTest set: Average Loss: {} Average Accuracy: {}/{} ({:8.6f}%)\n'.format(
test_loss,
correct, len(dataloader.dataset),
100. * correct / len(dataloader.dataset)))
loss = self.monitor.getvalues()
self.log_loss.update(loss)
missed_inputs = torch.cat(inc_inputs, 0)
loss['Test_Image'] = inputs[0]
loss['Test_Images'] = missed_inputs
self.visualizer.update(loss)
return test_loss, correct