Path: blob/master/site/en-snapshot/tensorboard/scalars_and_keras.ipynb
25115 views
Copyright 2019 The TensorFlow Authors.
TensorBoard Scalars: Logging training metrics in Keras
Overview
Machine learning invariably involves understanding key metrics such as loss and how they change as training progresses. These metrics can help you understand if you're overfitting, for example, or if you're unnecessarily training for too long. You may want to compare these metrics across different training runs to help debug and improve your model.
TensorBoard's Time Series Dashboard allows you to visualize these metrics using a simple API with very little effort. This tutorial presents very basic examples to help you learn how to use these APIs with TensorBoard when developing your Keras model. You will learn how to use the Keras TensorBoard callback and TensorFlow Summary APIs to visualize default and custom scalars.
Setup
Set up data for a simple regression
You're now going to use Keras to calculate a regression, i.e., find the best line of fit for a paired data set. (While using neural networks and gradient descent is overkill for this kind of problem, it does make for a very easy to understand example.)
You're going to use TensorBoard to observe how training and test loss change across epochs. Hopefully, you'll see training and test loss decrease over time and then remain steady.
First, generate 1000 data points roughly along the line y = 0.5x + 2. Split these data points into training and test sets. Your hope is that the neural net learns this relationship.
Training the model and logging loss
You're now ready to define, train and evaluate your model.
To log the loss scalar as you train, you'll do the following:
Create the Keras TensorBoard callback
Specify a log directory
Pass the TensorBoard callback to Keras' Model.fit().
TensorBoard reads log data from the log directory hierarchy. In this notebook, the root log directory is logs/scalars
, suffixed by a timestamped subdirectory. The timestamped subdirectory enables you to easily identify and select training runs as you use TensorBoard and iterate on your model.
Examining loss using TensorBoard
Now, start TensorBoard, specifying the root log directory you used above.
Wait a few seconds for TensorBoard's UI to spin up.
You may see TensorBoard display the message "No dashboards are active for the current data set". That's because initial logging data hasn't been saved yet. As training progresses, the Keras model will start logging data. TensorBoard will periodically refresh and show you your scalar metrics. If you're impatient, you can tap the Refresh arrow at the top right.
As you watch the training progress, note how both training and validation loss rapidly decrease, and then remain stable. In fact, you could have stopped training after 25 epochs, because the training didn't improve much after that point.
Hover over the graph to see specific data points. You can also try zooming in with your mouse, or selecting part of them to view more detail.
Notice the "Runs" selector on the left. A "run" represents a set of logs from a round of training, in this case the result of Model.fit(). Developers typically have many, many runs, as they experiment and develop their model over time.
Use the Runs selector to choose specific runs, or choose from only training or validation. Comparing runs will help you evaluate which version of your code is solving your problem better.
Ok, TensorBoard's loss graph demonstrates that the loss consistently decreased for both training and validation and then stabilized. That means that the model's metrics are likely very good! Now see how the model actually behaves in real life.
Given the input data (60, 25, 2), the line y = 0.5x + 2 should yield (32, 14.5, 3). Does the model agree?
Not bad!
Logging custom scalars
What if you want to log custom values, such as a dynamic learning rate? To do that, you need to use the TensorFlow Summary API.
Retrain the regression model and log a custom learning rate. Here's how:
Create a file writer, using
tf.summary.create_file_writer()
.Define a custom learning rate function. This will be passed to the Keras LearningRateScheduler callback.
Inside the learning rate function, use
tf.summary.scalar()
to log the custom learning rate.Pass the LearningRateScheduler callback to Model.fit().
In general, to log a custom scalar, you need to use tf.summary.scalar()
with a file writer. The file writer is responsible for writing data for this run to the specified directory and is implicitly used when you use the tf.summary.scalar()
.
Let's look at TensorBoard again.
Using the "Runs" selector on the left, notice that you have a <timestamp>/metrics
run. Selecting this run displays a "learning rate" graph that allows you to verify the progression of the learning rate during this run.
You can also compare this run's training and validation loss curves against your earlier runs. You might also notice that the learning rate schedule returned discrete values, depending on epoch, but the learning rate plot may appear smooth. TensorBoard has a smoothing parameter that you may need to turn down to zero to see the unsmoothed values.
How does this model do?
Batch-level logging
First let's load the MNIST dataset, normalize the data and write a function that creates a simple Keras model for classifying the images into 10 classes.
Instantaneous batch-level logging
Logging metrics at the batch level instantaneously can show us the level of fluctuation between batches while training in each epoch, which can be useful for debugging.
Setting up a summary writer to a different log directory:
To enable batch-level logging, custom tf.summary
metrics should be defined by overriding train_step()
in the Model's class definition and enclosed in a summary writer context. This can simply be made combined into subclassed Model definitions or can extend to edit our previous Functional API Model, as shown below:
Define our TensorBoard callback to log both epoch-level and batch-level metrics to our log directory and call model.fit()
with our selected batch_size
:
Open TensorBoard with the new log directory and see both the epoch-level and batch-level metrics:
Cumulative batch-level logging
Batch-level logging can also be implemented cumulatively, averaging each batch's metrics with those of previous batches and resulting in a smoother training curve when logging batch-level metrics.
Setting up a summary writer to a different log directory:
Create stateful metrics that can be logged per batch:
As before, add custom tf.summary
metrics in the overridden train_step
method. To make the batch-level logging cumulative, use the stateful metrics we defined to calculate the cumulative result given each training step's data.
As before, define our TensorBoard callback and call model.fit()
with our selected batch_size
:
Open TensorBoard with the new log directory and see both the epoch-level and batch-level metrics:
That's it! You now know how to create custom training metrics in TensorBoard for a wide variety of use cases.