From d852c2d7725ac0a8bacede622680bf6e6456926b Mon Sep 17 00:00:00 2001 From: Andrey M Date: Sun, 18 Jun 2017 23:21:39 +0200 Subject: [PATCH] Replace plot_loss_callback example with json_logging_callback (#4116) (#6941) The original plotting example doesn't work and a working version is somewhat too involved for a lambda. --- keras/callbacks.py | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/keras/callbacks.py b/keras/callbacks.py index a923bc0a28d7..40aba5c738ba 100644 --- a/keras/callbacks.py +++ b/keras/callbacks.py @@ -976,7 +976,7 @@ def on_train_end(self, logs=None): class LambdaCallback(Callback): - """Callback for creating simple, custom callbacks on-the-fly. + r"""Callback for creating simple, custom callbacks on-the-fly. This callback is constructed with anonymous functions that will be called at the appropriate time. Note that the callbacks expects positional @@ -1003,12 +1003,15 @@ class LambdaCallback(Callback): batch_print_callback = LambdaCallback( on_batch_begin=lambda batch,logs: print(batch)) - # Plot the loss after every epoch. - import numpy as np - import matplotlib.pyplot as plt - plot_loss_callback = LambdaCallback( - on_epoch_end=lambda epoch, logs: plt.plot(np.arange(epoch), - logs['loss'])) + # Stream the epoch loss to a file in JSON format. The file content + # is not well-formed JSON but rather has a JSON object per line. + import json + json_log = open('loss_log.json', mode='wt', buffering=1) + json_logging_callback = LambdaCallback( + on_epoch_end=lambda epoch, logs: json_log.write( + json.dumps({'epoch': epoch, 'loss': logs['loss']}) + '\n'), + on_train_end=lambda logs: json_log.close() + ) # Terminate some processes after having finished model training. processes = ... @@ -1018,7 +1021,7 @@ class LambdaCallback(Callback): model.fit(..., callbacks=[batch_print_callback, - plot_loss_callback, + json_logging_callback, cleanup_callback]) ``` """