/
callbacks.py
395 lines (316 loc) · 11 KB
/
callbacks.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
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
""" Callback module is adapted from the Keras library """
import six
import csv
import io
import os
import numpy as np
from collections import Iterable
from collections import OrderedDict
# compatible with both Python 2 and 3
try:
FileNotFoundError
except NameError:
FileNotFoundError = IOError
def get_history(callbacks):
"""
Gets the History callback from a list of callbacks.
# Argumetns:
callbacks (list | CallbackList): a list of callbacks
# Returns:
A History callback object or None if it was not found.
"""
history = None
for c in callbacks:
if isinstance(c, History):
history = c
break
return history
class Callback(object):
"""
Abstract base class used to build new callbacks.
# Properties
engine: instance of a PySHAC Engine.
Reference of the model being trained.
The `logs` dictionary that callback methods
take as argument will contain keys for quantities relevant to
the current batch or epoch.
"""
def __init__(self):
self.engine = None
def set_engine(self, engine):
"""
Sets an instance of a PySHAC Engine.
# Arguments:
engine (AbstractSHAC): A concrete implementation of the
SHAC engine.
"""
self.engine = engine
def on_train_begin(self, logs=None):
"""
Called at the beginning of training.
# Arguments
logs (dict | None): dictionary of logs.
"""
pass
def on_train_end(self, logs=None):
"""
Called at the end of training.
# Arguments
logs (dict | None): dictionary of logs.
"""
pass
def on_epoch_begin(self, epoch, logs=None):
"""
Called at the start of an epoch.
# Arguments
epoch (int): index of epoch.
logs (dict | None): dictionary of logs.
"""
pass
def on_epoch_end(self, epoch, logs=None):
"""
Called at the end of an epoch.
# Arguments
epoch (int): index of epoch.
logs (dict | None): dictionary of logs.
"""
pass
def on_evaluation_begin(self, params, logs=None):
"""
Called before the generated parameters are evaluated.
# Arguments:
params (list(OrderedDict)): A list of OrderedDicts,
such that each item is a dictionary of the names
and sampled values of a HyperParemeterList.
logs (dict | None): dictionary of logs.
"""
pass
def on_evaluation_ended(self, evaluations, logs=None):
"""
Called after the generated parameters are evaluated.
# Arguments:
evaluations (list(float)): A list of floating point
values, corresponding to the provided parameter
settings.
logs (dict | None): dictionary of logs.
"""
pass
def on_dataset_changed(self, dataset, logs=None):
"""
Called with the dataset maintained by the engine is
updated with new samples or data.
# Arguments:
dataset (Dataset): A Dataset object which contains
the history of sampled parameters and their
corresponding evaluation values.
logs (dict | None): dictionary of logs.
"""
pass
class CallbackList(Callback):
"""
Container abstracting a list of callbacks.
Automatically creates a History callback if not provided in
list of callbacks.
# Arguments
callbacks (list | None): List of `Callback` instances.
"""
def __init__(self, callbacks=None):
super(CallbackList, self).__init__()
callbacks = callbacks or []
# check if list has History callback in it
history = get_history(callbacks)
if history is None:
callbacks.append(History())
self.callbacks = [c for c in callbacks]
def append(self, callback):
"""
Appends an additional callback to the callback list.
# Arguments:
callback (Callback):
"""
self.callbacks.append(callback)
def set_engine(self, engine):
"""
Sets an instance of a PySHAC Engine.
# Arguments:
engine (AbstractSHAC): A concrete implementation of the
SHAC engine.
"""
for callback in self.callbacks:
callback.set_engine(engine)
def on_train_begin(self, logs=None):
"""
Called at the beginning of training.
# Arguments
logs (dict | None): dictionary of logs.
"""
logs = logs or {}
for callback in self.callbacks:
callback.on_train_begin(logs)
def on_train_end(self, logs=None):
"""
Called at the end of training.
# Arguments
logs (dict | None): dictionary of logs.
"""
logs = logs or {}
for callback in self.callbacks:
callback.on_train_end(logs)
def on_epoch_begin(self, epoch, logs=None):
"""
Called at the start of an epoch.
# Arguments
epoch (int): index of epoch.
logs (dict | None): dictionary of logs.
"""
logs = logs or {}
for callback in self.callbacks:
callback.on_epoch_begin(epoch, logs)
def on_epoch_end(self, epoch, logs=None):
"""
Called at the end of an epoch.
# Arguments
epoch (int): index of epoch.
logs (dict | None): dictionary of logs.
"""
logs = logs or {}
for callback in self.callbacks:
callback.on_epoch_end(epoch, logs)
def on_evaluation_begin(self, params, logs=None):
"""
Called before the generated parameters are evaluated.
# Arguments:
params (list(OrderedDict)): A list of OrderedDicts,
such that each item is a dictionary of the names
and sampled values of a HyperParemeterList.
logs (dict | None): dictionary of logs.
"""
logs = logs or {}
for callback in self.callbacks:
callback.on_evaluation_begin(params, logs)
def on_evaluation_ended(self, evaluations, logs=None):
"""
Called after the generated parameters are evaluated.
# Arguments:
evaluations (list(float)): A list of floating point
values, corresponding to the provided parameter
settings.
logs (dict | None): dictionary of logs.
"""
logs = logs or {}
for callback in self.callbacks:
callback.on_evaluation_ended(evaluations, logs)
def on_dataset_changed(self, dataset, logs=None):
"""
Called with the dataset maintained by the engine is
updated with new samples or data.
# Arguments:
dataset (Dataset): A Dataset object which contains
the history of sampled parameters and their
corresponding evaluation values.
logs (dict | None): dictionary of logs.
"""
logs = logs or {}
for callback in self.callbacks:
callback.on_dataset_changed(dataset, logs)
def __iter__(self):
return iter(self.callbacks)
class History(Callback):
"""
Callback that records events into a `History` object.
This callback is automatically applied to
every engine. The `History` object
gets returned by the `fit` or `fit_dataset` methods.
"""
def __init__(self):
super(History, self).__init__()
def on_train_begin(self, logs=None):
"""
Initializes the epoch list and history dictionary.
# Arguments:
logs (dict | None): dictionary of logs.
"""
self.epochs = []
self.history = logs or {}
def on_epoch_end(self, epoch, logs=None):
"""
Adds the current epoch's log values to the history.
# Arguments:
epoch (int): index of epoch.
logs (dict | None): dictionary of logs.
"""
logs = logs or {}
self.epochs.append(epoch)
for k, v in logs.items():
self.history.setdefault(k, []).append(v)
class CSVLogger(Callback):
"""
Callback that streams epoch results to a csv file.
Supports all values that can be represented as a string,
including 1D iterables such as np.ndarray.
# Example
```python
csv_logger = CSVLogger('training.log')
shac.fit(evaluation_function, callbacks=[csv_logger])
```
# Arguments
filename (str): filename of the csv file, e.g. 'run/log.csv'.
separator (str): string used to separate elements in the csv file.
append (bool): True: append if file exists (useful for continuing
training). False: overwrite existing file,
"""
def __init__(self, filename, separator=',', append=False):
super(CSVLogger, self).__init__()
self.sep = separator
self.filename = filename
self.append = append
self.writer = None
self.keys = None
self.append_header = True
if six.PY2:
self.file_flags = 'b'
self._open_args = {}
else:
self.file_flags = ''
self._open_args = {'newline': '\n'}
def on_train_begin(self, logs=None):
if self.append:
if os.path.exists(self.filename):
with open(self.filename, 'r' + self.file_flags) as f:
self.append_header = not bool(len(f.readline()))
mode = 'a'
else:
mode = 'w'
self.csv_file = io.open(self.filename,
mode + self.file_flags,
**self._open_args)
def on_epoch_end(self, epoch, logs=None):
logs = logs or {}
def handle_value(k):
is_zero_dim_ndarray = isinstance(k, np.ndarray) and k.ndim == 0
if isinstance(k, six.string_types):
return k
elif isinstance(k, Iterable) and not is_zero_dim_ndarray:
return '"[%s]"' % (', '.join(map(str, k)))
else:
return k
if self.keys is None:
self.keys = sorted(logs.keys())
if 'model' in self.keys:
self.keys.remove('model')
if not self.writer:
class CustomDialect(csv.excel):
delimiter = self.sep
fieldnames = ['epoch'] + self.keys
self.writer = csv.DictWriter(self.csv_file,
fieldnames=fieldnames,
dialect=CustomDialect)
if self.append_header:
self.writer.writeheader()
row_dict = OrderedDict({'epoch': epoch})
row_dict.update((key, handle_value(logs[key])) for key in self.keys)
self.writer.writerow(row_dict)
self.csv_file.flush()
def on_train_end(self, logs=None):
self.csv_file.close()
self.writer = None