TensorBoard
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
TensorBoard is the visualisation tool of the TensorFlow ecosystem: it reads event files written during training and shows scalar curves, the model graph, weight histograms, images, text, embeddings and profiler traces in a browser. This page shows the Keras callback, writing summaries yourself in a custom loop, how to launch the UI locally, in a notebook and on a remote machine, and how to organise runs. Profiling views are expanded on Performance, XLA and Profiling; callbacks in general are on Callbacks; the PyTorch integration is TensorBoard Integration and broader tooling is in Experiment Tracking and MLOps.
It targets Python 3.13 and TensorFlow 2.21 with Keras 3.15 (TensorFlow 2.22 is "upcoming" and not covered), and was checked against the official documentation on 2026-10-30. Examples were run on Python 3.13 with TensorFlow 2.21, Keras 3.15 and TensorBoard 2.21 (CPU) on 2026-10-31. Snippets that continue an earlier example, or use names such as model and train_ds defined elsewhere, were run with small synthetic stand-ins. The notebook magics need Jupyter or Colab and were not executed.
Installing TensorBoard
TensorFlow 2.21 does not depend on the tensorboard package, so pip install tensorflow does not install it. Install it with pip install tensorboard. Besides the UI, it provides the implementation behind the tf.summary scalar, image, histogram and text functions. Without it, tf.summary.create_file_writer still creates an event file, but tf.summary.scalar (and histogram, image, text) raise TBNotInstalledError: TensorBoard is not installed, missing implementation for tf.summary.scalar. The keras.callbacks.TensorBoard callback can be created, but fit() raises the same error the first time the callback writes a metric.
The Keras TensorBoard callback
import datetime
import keras
log_dir = "logs/fit/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
tensorboard_cb = keras.callbacks.TensorBoard(
log_dir=log_dir,
histogram_freq=1, # weight and bias histograms every epoch (0 disables)
write_graph=True, # log the model graph
update_freq="epoch", # "epoch", "batch" or an integer number of batches
profile_batch=0, # 0 disables the profiler; (10, 20) profiles those batches
)
model.fit(
x_train, y_train,
epochs=5,
validation_data=(x_test, y_test),
callbacks=[tensorboard_cb],
)
Source: https://www.tensorflow.org/tensorboard/get_started and https://keras.io/api/callbacks/tensorboard/
Arguments worth knowing (all of them are accepted by the Keras 3.15 callback used above):
-
log_dir: use a fresh timestamped subdirectory per run so TensorBoard can overlay runs; reusing a directory mixes events from different runs. -
histogram_freq: epochs between weight histograms; off by default. -
write_graph: whether to log the model graph for the Graphs dashboard. -
update_freq:"epoch"writes metrics once per epoch,"batch"or an integer writes more often at the cost of speed and disk. -
profile_batch: batch or range to profile; see the profiler page. -
Keras 3 note: callback options that depended on the TensorFlow 1 style graph or on
write_imagesand embeddings may behave differently or be unavailable on non-TensorFlow backends. The callback is documented for all backends, but the profiler and graph views are TensorFlow-specific.
Launching TensorBoard
pip install tensorboard # not installed with TensorFlow 2.21; the profile tab also needs tensorboard-plugin-profile
tensorboard --logdir logs/fit # then open http://localhost:6006
tensorboard --logdir logs/fit --port 6007
tensorboard --logdir_spec baseline:logs/a,tuned:logs/b # name runs from different roots
# In Jupyter or Colab
%load_ext tensorboard
%tensorboard --logdir logs/fit
By default TensorBoard 2.21 listens on localhost only; at start it prints "Serving TensorBoard on localhost; to expose to the network, use a proxy or pass --bind_all". With --logdir_spec each run is listed under its name prefix, such as baseline/<run> and tuned/<run>. On a remote machine forward the port through SSH (ssh -L 6006:localhost:6006 user@host) rather than exposing the server publicly, since TensorBoard has no built-in authentication. TensorBoard reads log directories on cloud storage too (for example gs:// paths) when the corresponding filesystem support is installed.
Writing summaries yourself
In a custom loop (see Writing a Training Loop from Scratch and A Training Loop with TF Core) create one file writer per run and split, then call tf.summary functions with a step number inside the writer’s context.
import datetime
import numpy as np
import tensorflow as tf
import keras
stamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
train_writer = tf.summary.create_file_writer(f"logs/gradient_tape/{stamp}/train")
test_writer = tf.summary.create_file_writer(f"logs/gradient_tape/{stamp}/test")
train_loss = keras.metrics.Mean(name="train_loss")
train_acc = keras.metrics.SparseCategoricalAccuracy(name="train_accuracy")
for epoch in range(5):
for x, y in train_ds:
train_step(x, y) # updates train_loss and train_acc
with train_writer.as_default():
tf.summary.scalar("loss", train_loss.result(), step=epoch)
tf.summary.scalar("accuracy", train_acc.result(), step=epoch)
# Other summary types
tf.summary.histogram("logits", model(x_batch, training=False), step=epoch)
tf.summary.image("inputs", x_batch[:6], max_outputs=6, step=epoch) # [N, H, W, C]
tf.summary.text("note", f"epoch {epoch}", step=epoch)
with test_writer.as_default():
tf.summary.scalar("loss", evaluate_loss(), step=epoch)
train_loss.reset_state()
train_acc.reset_state()
Key rules:
-
Metrics are accumulated with stateful
keras.metricsobjects, logged once per epoch, and reset withreset_state()(see Metrics). -
Using the same tag (
loss) in two sibling writers (trainandtest) overlays the curves in one chart, which is the idiomatic way to compare training and validation. -
tf.summary.imageexpects a four-dimensional tensor[batch, height, width, channels]with values in [0, 1] for floats or [0, 255] for integers.tf.summary.histogramtakes any tensor andtf.summary.texta string tensor. These three functions are described in the API reference rather than the getting-started page. -
Summaries inside a
tf.functionwork when a default writer is active at trace time; pass the step as a tensor or atf.Variableso it is not frozen in the graph. -
Call
writer.flush()before reading the logs from another process if data seems missing.
Dashboards
| Dashboard | Content |
|---|---|
Time Series, Scalars |
loss, metrics, learning rate and any |
Graphs |
the model graph ( |
Histograms, Distributions |
how weight and activation values change over training |
Images, Text |
logged image and text samples, useful for augmentation checks and generated output |
Profile |
profiler tools such as the input pipeline analyzer, see Performance, XLA and Profiling |
HParams |
compare hyperparameter runs, see below |
Other dashboards appear when you log other data types; inactive ones are listed in the "Inactive" dropdown at the top right.
Logging hyperparameters
The HParams plugin records the hyperparameters of each run next to its final metrics so runs can be compared in a table and a parallel-coordinates view. It is the natural companion of Hyperparameter Tuning with KerasTuner.
from tensorboard.plugins.hparams import api as hp
hparams = {"units": 128, "dropout": 0.2, "lr": 1e-3}
with tf.summary.create_file_writer(f"logs/hparam_tuning/run-{run_id}").as_default():
hp.hparams(hparams) # record this run's configuration
accuracy = train_and_evaluate(hparams)
tf.summary.scalar("accuracy", accuracy, step=1)
Practical advice
-
Keep one directory per experiment and one subdirectory per run; delete or move old runs rather than pointing TensorBoard at a huge tree, which slows loading.
-
Log less often for large models: per-batch scalars every step produce large event files; use
update_freqwith an integer. -
Do not log from every worker in distributed training; log from the chief only (Distributed Training).
-
TensorBoard is local-first; for team dashboards, artifact tracking and model registries consider the hosted tools in Experiment Tracking and MLOps.
-
Combine with
ModelCheckpointandEarlyStoppingin the same callback list (Callbacks). -
Older material uses
tf.summary.FileWriterandtf.contrib.summary; both belong to TensorFlow 1 and are gone. Usetf.summary.create_file_writer.
References
-
TensorBoard, Get started: https://www.tensorflow.org/tensorboard/get_started
-
TensorBoard, Hyperparameter tuning with the HParams dashboard: https://www.tensorflow.org/tensorboard/hyperparameter_tuning_with_hparams
-
TensorBoard, Scalars, graphs and images guides: https://www.tensorflow.org/tensorboard
-
Keras API, TensorBoard callback: https://keras.io/api/callbacks/tensorboard/
-
TensorBoard on PyPI: https://pypi.org/project/tensorboard/