text
stringlengths
0
4.99k
0. 0. 0. 0. 0. 0. 0.
1.0986123 0. 0. 0. 0. 0. 0.
0. 1.0986123 1.0986123 0. 0. 0. ]]
Model output: tf.Tensor([[-0.49451536]], shape=(1, 1), dtype=float32)Writing your own callbacks
Authors: Rick Chao, Francois Chollet
Date created: 2019/03/20
Last modified: 2020/04/15
Description: Complete guide to writing new Keras callbacks.
View in Colab • GitHub source
Introduction
A callback is a powerful tool to customize the behavior of a Keras model during training, evaluation, or inference. Examples include tf.keras.callbacks.TensorBoard to visualize training progress and results with TensorBoard, or tf.keras.callbacks.ModelCheckpoint to periodically save your model during training.
In this guide, you will learn what a Keras callback is, what it can do, and how you can build your own. We provide a few demos of simple callback applications to get you started.
Setup
import tensorflow as tf
from tensorflow import keras
Keras callbacks overview
All callbacks subclass the keras.callbacks.Callback class, and override a set of methods called at various stages of training, testing, and predicting. Callbacks are useful to get a view on internal states and statistics of the model during training.
You can pass a list of callbacks (as the keyword argument callbacks) to the following model methods:
keras.Model.fit()
keras.Model.evaluate()
keras.Model.predict()
An overview of callback methods
Global methods
on_(train|test|predict)_begin(self, logs=None)
Called at the beginning of fit/evaluate/predict.
on_(train|test|predict)_end(self, logs=None)
Called at the end of fit/evaluate/predict.
Batch-level methods for training/testing/predicting
on_(train|test|predict)_batch_begin(self, batch, logs=None)
Called right before processing a batch during training/testing/predicting.
on_(train|test|predict)_batch_end(self, batch, logs=None)
Called at the end of training/testing/predicting a batch. Within this method, logs is a dict containing the metrics results.
Epoch-level methods (training only)
on_epoch_begin(self, epoch, logs=None)
Called at the beginning of an epoch during training.
on_epoch_end(self, epoch, logs=None)
Called at the end of an epoch during training.
A basic example
Let's take a look at a concrete example. To get started, let's import tensorflow and define a simple Sequential Keras model:
# Define the Keras model to add callbacks to
def get_model():
model = keras.Sequential()
model.add(keras.layers.Dense(1, input_dim=784))
model.compile(
optimizer=keras.optimizers.RMSprop(learning_rate=0.1),
loss="mean_squared_error",
metrics=["mean_absolute_error"],
)
return model
Then, load the MNIST data for training and testing from Keras datasets API:
# Load example MNIST data and pre-process it
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
x_train = x_train.reshape(-1, 784).astype("float32") / 255.0
x_test = x_test.reshape(-1, 784).astype("float32") / 255.0
# Limit the data to 1000 samples
x_train = x_train[:1000]
y_train = y_train[:1000]
x_test = x_test[:1000]
y_test = y_test[:1000]
Now, define a simple custom callback that logs:
When fit/evaluate/predict starts & ends
When each epoch starts & ends
When each training batch starts & ends
When each evaluation (test) batch starts & ends
When each inference (prediction) batch starts & ends
class CustomCallback(keras.callbacks.Callback):
def on_train_begin(self, logs=None):
keys = list(logs.keys())
print("Starting training; got log keys: {}".format(keys))
def on_train_end(self, logs=None):
keys = list(logs.keys())
print("Stop training; got log keys: {}".format(keys))
def on_epoch_begin(self, epoch, logs=None):
keys = list(logs.keys())
print("Start epoch {} of training; got log keys: {}".format(epoch, keys))
def on_epoch_end(self, epoch, logs=None):
keys = list(logs.keys())
print("End epoch {} of training; got log keys: {}".format(epoch, keys))
def on_test_begin(self, logs=None):
keys = list(logs.keys())