forked from spMohanty/tortilla
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmonitor.py
More file actions
359 lines (324 loc) · 10.4 KB
/
monitor.py
File metadata and controls
359 lines (324 loc) · 10.4 KB
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
#!/usr/bin/env python
from utils import accuracy
import numpy as np
from sklearn.metrics import confusion_matrix
from sklearn.preprocessing import normalize
from datastream import TortillaDataStream
from plotter import TortillaLinePlotter, TortillaHeatMapPlotter, \
TortillaImagesPlotter, TortillaBarGraphPlotter, \
VisdomTest
import os
import json
class TortillaMonitor:
"""
Monitors the
- (top-k) train accuracy
- (top-k) val accuracy
- train loss
- val loss
- Train Confusion Matrix
- Val confusion Matrix
- training data distribution
"""
def __init__(self, experiment_name, plot=True, topk=(1,5),
dataset=False, classes=[], config=None,
use_gpu=False):
self.experiment_name = experiment_name
self.plot = plot
self.topk = topk
self.classes = classes
self.config = config
self.use_gpu = use_gpu
self.dataset = dataset
# Filter top-k to ensure that all values are >0 and less than
# the number of classes
_topk = []
for tk in self.config.topk:
if tk <= len(self.classes) and tk > 0:
_topk.append(tk)
self.topk = _topk
self.config.topk = self.topk
if self.config.plot_platform == 'none':
self.plot = False
if self.plot:
if self.config.plot_platform == 'visdom' :
VisdomTest(server=self.config.visdom_server, port=self.config.visdom_port)
self._init_plotters()
self._init_data_gatherers()
def _init_plotters(self):
topklabels = ["top-"+str(x) for x in self.topk]
self.train_accuracy_plotter = TortillaLinePlotter(
experiment_name=self.experiment_name,
fields=topklabels,
title='train-accuracy',
opts=dict(
xtickmin = 0,
xtickmax = self.config.epochs,
ytickmin = 0,
ytickmax = 100,
xlabel="Epochs",
ylabel="Accuracy"
),
platform=self.config.plot_platform,
server=self.config.visdom_server,
port=self.config.visdom_port
)
self.val_accuracy_plotter = TortillaLinePlotter(
experiment_name=self.experiment_name,
fields=topklabels,
title='val-accuracy',
opts = dict(
xtickmin = 0,
xtickmax = self.config.epochs,
ytickmin = 0,
ytickmax = 100,
xlabel="Epochs",
ylabel="Accuracy",
markers=True
),
platform=self.config.plot_platform,
server=self.config.visdom_server,
port=self.config.visdom_port
)
self.loss_plotter = TortillaLinePlotter(
experiment_name=self.experiment_name,
fields=['train_loss', 'val_loss'],
title='Loss',
opts = dict(
xtickmin = 0,
xtickmax = self.config.epochs,
xlabel="Epochs",
ylabel="Loss",
markers=True
),
platform=self.config.plot_platform,
server=self.config.visdom_server,
port=self.config.visdom_port
)
self.val_confusion_matrix_plotter = TortillaHeatMapPlotter(
experiment_name=self.experiment_name,
fields=self.classes,
title='Latest Validation Confusion Matrix',
opts = dict(
rownames=self.classes,
columnnames=self.classes
),
platform=self.config.plot_platform,
server=self.config.visdom_server,
port=self.config.visdom_port
)
self.images_plotter = TortillaImagesPlotter(
experiment_name=self.experiment_name,
title='Images',
platform=self.config.plot_platform,
server=self.config.visdom_server,
port=self.config.visdom_port
)
self.learning_rate_plotter = TortillaLinePlotter(
experiment_name=self.experiment_name,
fields=['learning_rate', 'na'],
title='Learning Rate',
opts = dict(
xtickmin=0,
xtickmax=self.config.epochs,
xlabel="Epochs",
ylabel="Learning Rate",
markers=False
),
platform=self.config.plot_platform,
server=self.config.visdom_server,
port=self.config.visdom_port
)
if self.dataset:
#Plot data distribution
self.data_distribution_plotter = TortillaBarGraphPlotter(
experiment_name=self.experiment_name,
title='Training Data Distribution',
platform=self.config.plot_platform,
server=self.config.visdom_server,
port=self.config.visdom_port
)
training_labels = list(self.dataset.meta["train_class_frequency"].keys())
training_values = [
self.dataset.meta["train_class_frequency"][key] \
for key in training_labels
]
self.data_distribution_plotter.update_bar_graph(
values=np.array(training_values),
field_names = training_labels
)
def _init_data_gatherers(self):
topklabels = ["top-"+str(x) for x in self.topk]
self.train_accuracy = TortillaDataStream(
name="train-accuracy",
column_names=topklabels
)
self.val_accuracy = TortillaDataStream(
name="val-accuracy",
column_names=topklabels
)
self.train_epochs = TortillaDataStream(
name="train-epochs",
column_names=['epochs']
)
self.val_epochs = TortillaDataStream(
name="val-epochs",
column_names=['epochs']
)
self.train_loss = TortillaDataStream(
name="train-loss",
column_names=['loss']
)
self.val_loss = TortillaDataStream(
name="val-loss",
column_names=['loss']
)
self.train_confusion_matrix = TortillaDataStream(
name="train-confusion_matrix",
merge_mode="sum"
)
self.val_confusion_matrix = TortillaDataStream(
name="val-confusion_matrix",
merge_mode="sum"
)
self.learning_rate = TortillaDataStream(
name="learning_rate",
column_names=['learning_rate']
)
def compute_confusion_matrix(self, outputs, labels):
_, pred_top_1 = outputs.topk(1, 1, True, True)#compute top-1 predictions
pred_top_1 = pred_top_1.t()
if self.use_gpu:
_labels = labels.data.cpu().numpy()
_preds = pred_top_1.data.cpu().numpy()[0]
else:
_labels = labels.data.numpy()
_preds = pred_top_1.data.numpy()[0]
_batch_confusion_matrix = confusion_matrix(_labels, _preds, labels=range(len(self.classes)))
return _batch_confusion_matrix
def _compute_and_register_stats(self, epoch, outputs, labels,
loss, learning_rate=False, train=True):
_accuracy = accuracy(outputs, labels, topk=self.topk)
_accuracy = np.array([x.data[0] for x in _accuracy])
_batch_confusion_matrix = self.compute_confusion_matrix(outputs, labels)
if train:
accuracy_stream = self.train_accuracy
epoch_stream = self.train_epochs
loss_stream = self.train_loss
confusion_matrix_stream = self.train_confusion_matrix
else:
accuracy_stream = self.val_accuracy
epoch_stream = self.val_epochs
loss_stream = self.val_loss
confusion_matrix_stream = self.val_confusion_matrix
accuracy_stream.add_to_buffer(_accuracy)
epoch_stream.add_to_buffer(epoch)
loss_stream.add_to_buffer(loss.data[0])
confusion_matrix_stream.add_to_buffer(_batch_confusion_matrix)
if learning_rate:
self.learning_rate.add_to_buffer(learning_rate)
def _flush_stats(self, train=True):
"""
Flush all the data from the datastream_buffers into the actual
datastreams
"""
if train:
self.train_accuracy.flush_buffer()
self.train_epochs.flush_buffer()
self.train_loss.flush_buffer()
self.train_confusion_matrix.flush_buffer()
self.learning_rate.flush_buffer()
else:
self.val_accuracy.flush_buffer()
self.val_epochs.flush_buffer()
self.val_loss.flush_buffer()
self.val_confusion_matrix.flush_buffer()
if self.plot:
self._plot(train=train)
def _dump_states(self, train=True):
"""
Pickles and saves all the datastreams
"""
prefix = self.config.experiment_dir_name+"/datastreams/"
try:
os.mkdir(prefix)
except:
pass
prefix += "{}.pickle"
if train:
self.train_accuracy.dump(prefix.format("train_accuracy"))
self.train_epochs.dump(prefix.format("train_epochs"))
self.train_loss.dump(prefix.format("train_loss"))
self.train_confusion_matrix.dump(prefix.format("train_confusion_matrix"))
self.learning_rate.dump(prefix.format("learning_rate"))
else:
self.val_accuracy.dump(prefix.format("val_accuracy"))
self.val_epochs.dump(prefix.format("val_epochs"))
self.val_loss.dump(prefix.format("val_loss"))
self.val_confusion_matrix.dump(prefix.format("val_confusion_matrix"))
"""
Save dataset specific metadata into experiment dir
"""
# TODO: Redo this with more information from dataset meta.json file
meta_path = self.config.experiment_dir_name+"/meta.json"
_meta = {}
_meta["classes"] = self.classes
_meta["plot_platform"] = self.config.plot_platform
# _meta["dataset_dir"] = self.dataset.dataset_folder
if not os.path.exists(meta_path):
fp = open(meta_path, "w")
fp.write(json.dumps(_meta))
fp.close()
def _plot(self, train=True):
#The actual plot happens on every buffer flush
if train:
# A check to ensure that it doesnt throw errors when
# the buffer is empty
if self.train_epochs.get_last() == None:
print("Empty Buffer in Train. Ignoring...")
return
self.train_accuracy_plotter.append_plot(
self.train_accuracy.get_last(),
self.train_epochs.get_last()
)
_payload = {}
_payload["train_loss"] = self.train_loss.get_last()
self.loss_plotter.append_plot_with_dict(
_payload,
self.train_epochs.get_last()
)
_payload = {}
_payload["learning_rate"] = self.learning_rate.get_last()
self.learning_rate_plotter.append_plot_with_dict(
_payload,
self.train_epochs.get_last()
)
else:
# A check to ensure that it doesnt throw errors when
# the buffer is empty
if self.val_epochs.get_last() == None:
print("Empty Buffer in Val. Ignoring...")
return
self.val_accuracy_plotter.append_plot(
self.val_accuracy.get_last(),
self.val_epochs.get_last()
)
_payload = {}
_payload["val_loss"] = self.val_loss.get_last()
self.loss_plotter.append_plot_with_dict(
_payload,
self.val_epochs.get_last()
)
last_confusion_matrix = self.val_confusion_matrix.get_last()
# Normalize confusion matrix
if self.config.normalize_confusion_matrix:
axis_sum = last_confusion_matrix.sum(axis=1) + 1e-20
last_confusion_matrix = last_confusion_matrix.astype('float')/axis_sum[:, np.newaxis]
last_confusion_matrix = np.ndarray.clip(last_confusion_matrix, 0, 1)
self.val_confusion_matrix_plotter.update_plot(
last_confusion_matrix
)
def main():
monitor = TortillaMonitor(topk=(1,5,), plotter=None, classes=[])
if __name__ == "__main__":
main()