Custom Callback After Each Epoch To Log Certain Information
Solution 1:
Here is the solution, by subclassing Callback
:
from keras.callbacks import Callback
classMyLogger(Callback):
defon_epoch_end(self, epoch, logs=None):
withopen('log.txt', 'a+') as f:
f.write('%02d %.3f\n' % (epoch, logs['loss']))
then
mylogger = MyLogger()
model.fit(X, Y, batch_size=32, epochs=32, verbose=1, callbacks=[mylogger])
or even
model.fit(X, Y, batch_size=32, epochs=32, verbose=1, callbacks=[MyLogger()])
Solution 2:
Actually, you don't need to define a function (or even use an explicit callback) for this, as such info is automatically returned by the fit
method; from the docs:
History
keras.callbacks.History()
Callback that records events into a
History
object.This callback is automatically applied to every Keras model. The
History
object gets returned by thefit
method of models.
You don't even need to explicitly import anything; what you need is just:
hist = model.fit(X, Y, batch_size=4, epochs=32, verbose=1, callbacks=[savemodel]) # no other specific callback
and hist.history
will contain the loss and any other metrics of interest you may have defined (e.g. accuracy), for the training and validation (if exists) sets, at the end of each epoch, which you can subsequently save into a file.
See here for detailed examples.
Post a Comment for "Custom Callback After Each Epoch To Log Certain Information"