{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "TsHV-7cpVkyK" }, "source": [ "##### Copyright 2019 The TensorFlow Authors." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "atWM-s8yVnfX" }, "outputs": [], "source": [ "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", "# https://www.apache.org/licenses/LICENSE-2.0\n", "#\n", "# Unless required by applicable law or agreed to in writing, software\n", "# distributed under the License is distributed on an \"AS IS\" BASIS,\n", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n", "# See the License for the specific language governing permissions and\n", "# limitations under the License." ] }, { "cell_type": "markdown", "metadata": { "id": "TB0wBWfcVqHz" }, "source": [ "# Using TensorBoard in Notebooks\n", "\n", "\n", " \n", " \n", " \n", " \n", "
\n", " View on TensorFlow.org\n", " \n", " Run in Google Colab\n", " \n", " View source on GitHub\n", " \n", " Download notebook\n", "
" ] }, { "cell_type": "markdown", "metadata": { "id": "elH58gbhWAmn" }, "source": [ "TensorBoard can be used directly within notebook experiences such as [Colab](https://colab.research.google.com/) and [Jupyter](https://jupyter.org/). This can be helpful for sharing results, integrating TensorBoard into existing workflows, and using TensorBoard without installing anything locally." ] }, { "cell_type": "markdown", "metadata": { "id": "VszJNloY3ZU3" }, "source": [ "## Setup" ] }, { "cell_type": "markdown", "metadata": { "id": "E6QhA_dp3eRq" }, "source": [ "Start by installing TF 2.0 and loading the TensorBoard notebook extension:\n", "\n", "**For Jupyter users:** If you’ve installed Jupyter and TensorBoard into\n", "the same virtualenv, then you should be good to go. If you’re using a\n", "more complicated setup, like a global Jupyter installation and kernels\n", "for different Conda/virtualenv environments, then you must ensure that\n", "the `tensorboard` binary is on your `PATH` inside the Jupyter notebook\n", "context. One way to do this is to modify the `kernel_spec` to prepend\n", "the environment’s `bin` directory to `PATH`, [as described here][1].\n", "\n", "[1]: https://github.com/ipython/ipykernel/issues/395#issuecomment-479787997\n" ] }, { "cell_type": "markdown", "metadata": { "id": "9w7Baxc8aCtJ" }, "source": [ "**For Docker users:** In case you are running a [Docker](https://docs.docker.com/install/) image of [Jupyter Notebook server using TensorFlow's nightly](https://www.tensorflow.org/install/docker#examples_using_cpu-only_images), it is necessary to expose not only the notebook's port, but the TensorBoard's port. Thus, run the container with the following command:\n", "\n", "```\n", "docker run -it -p 8888:8888 -p 6006:6006 \\\n", "tensorflow/tensorflow:nightly-py3-jupyter \n", "```\n", "\n", "where the `-p 6006` is the default port of TensorBoard. This will allocate a port for you to run one TensorBoard instance. To have concurrent instances, it is necessary to allocate more ports. Also, pass `--bind_all` to `%tensorboard` to expose the port outside the container." ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "id": "8p3Tbx8cWEFA" }, "outputs": [], "source": [ "# Load the TensorBoard notebook extension\n", "%load_ext tensorboard" ] }, { "cell_type": "markdown", "metadata": { "id": "9GtR_cTTkf9G" }, "source": [ "Import TensorFlow, datetime, and os:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "mVtYvbbIWRkV" }, "outputs": [], "source": [ "import tensorflow as tf\n", "import datetime, os" ] }, { "cell_type": "markdown", "metadata": { "id": "Cu1fbH-S3oAX" }, "source": [ "## TensorBoard in notebooks" ] }, { "cell_type": "markdown", "metadata": { "id": "XfCa27_8kov6" }, "source": [ "Download the [FashionMNIST](https://github.com/zalandoresearch/fashion-mnist) dataset and scale it:" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "id": "z8b82G7YksOS" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/train-labels-idx1-ubyte.gz\n", "32768/29515 [=================================] - 0s 0us/step\n", "Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/train-images-idx3-ubyte.gz\n", "26427392/26421880 [==============================] - 0s 0us/step\n", "Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/t10k-labels-idx1-ubyte.gz\n", "8192/5148 [===============================================] - 0s 0us/step\n", "Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/t10k-images-idx3-ubyte.gz\n", "4423680/4422102 [==============================] - 0s 0us/step\n" ] } ], "source": [ "fashion_mnist = tf.keras.datasets.fashion_mnist\n", "\n", "(x_train, y_train),(x_test, y_test) = fashion_mnist.load_data()\n", "x_train, x_test = x_train / 255.0, x_test / 255.0" ] }, { "cell_type": "markdown", "metadata": { "id": "lBk1BqAZKEKd" }, "source": [ "Create a very simple model:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "OS7qGYiMKGQl" }, "outputs": [], "source": [ "def create_model():\n", " return tf.keras.models.Sequential([\n", " tf.keras.layers.Flatten(input_shape=(28, 28), name='layers_flatten'),\n", " tf.keras.layers.Dense(512, activation='relu', name='layers_dense'),\n", " tf.keras.layers.Dropout(0.2, name='layers_dropout'),\n", " tf.keras.layers.Dense(10, activation='softmax', name='layers_dense_2')\n", " ])" ] }, { "cell_type": "markdown", "metadata": { "id": "RNaPPs5ZKNOV" }, "source": [ "Train the model using Keras and the TensorBoard callback:" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "id": "lpUO9HqUKP6z" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Train on 60000 samples, validate on 10000 samples\n", "Epoch 1/5\n", "60000/60000 [==============================] - 11s 182us/sample - loss: 0.4976 - accuracy: 0.8204 - val_loss: 0.4143 - val_accuracy: 0.8538\n", "Epoch 2/5\n", "60000/60000 [==============================] - 10s 174us/sample - loss: 0.3845 - accuracy: 0.8588 - val_loss: 0.3855 - val_accuracy: 0.8626\n", "Epoch 3/5\n", "60000/60000 [==============================] - 10s 175us/sample - loss: 0.3513 - accuracy: 0.8705 - val_loss: 0.3740 - val_accuracy: 0.8607\n", "Epoch 4/5\n", "60000/60000 [==============================] - 11s 177us/sample - loss: 0.3287 - accuracy: 0.8793 - val_loss: 0.3596 - val_accuracy: 0.8719\n", "Epoch 5/5\n", "60000/60000 [==============================] - 11s 178us/sample - loss: 0.3153 - accuracy: 0.8825 - val_loss: 0.3360 - val_accuracy: 0.8782\n" ] } ], "source": [ "def train_model():\n", " \n", " model = create_model()\n", " model.compile(optimizer='adam',\n", " loss='sparse_categorical_crossentropy',\n", " metrics=['accuracy'])\n", "\n", " logdir = os.path.join(\"logs\", datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\"))\n", " tensorboard_callback = tf.keras.callbacks.TensorBoard(logdir, histogram_freq=1)\n", "\n", " model.fit(x=x_train, \n", " y=y_train, \n", " epochs=5, \n", " validation_data=(x_test, y_test), \n", " callbacks=[tensorboard_callback])\n", "\n", "train_model()" ] }, { "cell_type": "markdown", "metadata": { "id": "SxvXc4hoKW7d" }, "source": [ "Start TensorBoard within the notebook using [magics](https://ipython.readthedocs.io/en/stable/interactive/magics.html):" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "KBHp6M_zgjp4" }, "outputs": [], "source": [ "%tensorboard --logdir logs" ] }, { "cell_type": "markdown", "metadata": { "id": "Po7rTfQswAMT" }, "source": [ "" ] }, { "cell_type": "markdown", "metadata": { "id": "aQq3UHgmLBpC" }, "source": [ "You can now view dashboards such as **Time Series**, **Graphs**, **Distributions**, and others. Some dashboards are not available yet in Colab (such as the profile plugin).\n", "\n", "The `%tensorboard` magic has exactly the same format as the TensorBoard command line invocation, but with a `%`-sign in front of it." ] }, { "cell_type": "markdown", "metadata": { "id": "NiIMwOG8MR_g" }, "source": [ "You can also start TensorBoard before training to monitor it in progress:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "qyI5lrXoMw9K" }, "outputs": [], "source": [ "%tensorboard --logdir logs" ] }, { "cell_type": "markdown", "metadata": { "id": "ALxC8BbWWV91" }, "source": [ "" ] }, { "cell_type": "markdown", "metadata": { "id": "GUSM8yLrO2yZ" }, "source": [ "The same TensorBoard backend is reused by issuing the same command. If a different logs directory was chosen, a new instance of TensorBoard would be opened. Ports are managed automatically. \n", "\n", "Start training a new model and watch TensorBoard update automatically every 30 seconds or refresh it with the button on the top right:" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "id": "ixZlmtWhMyr4" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Train on 60000 samples, validate on 10000 samples\n", "Epoch 1/5\n", "60000/60000 [==============================] - 11s 184us/sample - loss: 0.4968 - accuracy: 0.8223 - val_loss: 0.4216 - val_accuracy: 0.8481\n", "Epoch 2/5\n", "60000/60000 [==============================] - 11s 176us/sample - loss: 0.3847 - accuracy: 0.8587 - val_loss: 0.4056 - val_accuracy: 0.8545\n", "Epoch 3/5\n", "60000/60000 [==============================] - 11s 176us/sample - loss: 0.3495 - accuracy: 0.8727 - val_loss: 0.3600 - val_accuracy: 0.8700\n", "Epoch 4/5\n", "60000/60000 [==============================] - 11s 179us/sample - loss: 0.3282 - accuracy: 0.8795 - val_loss: 0.3636 - val_accuracy: 0.8694\n", "Epoch 5/5\n", "60000/60000 [==============================] - 11s 176us/sample - loss: 0.3115 - accuracy: 0.8839 - val_loss: 0.3438 - val_accuracy: 0.8764\n" ] } ], "source": [ "train_model()" ] }, { "cell_type": "markdown", "metadata": { "id": "IlDz2oXBgnZ9" }, "source": [ "You can use the `tensorboard.notebook` APIs for a bit more control:" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "id": "ko9qeSQHLrEh" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Known TensorBoard instances:\n", " - port 6006: logdir logs (started 0:00:54 ago; pid 265)\n" ] } ], "source": [ "from tensorboard import notebook\n", "notebook.list() # View open TensorBoard instances" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "hzm9DNVILxJe" }, "outputs": [], "source": [ "# Control TensorBoard display. If no port is provided, \n", "# the most recently launched TensorBoard is used\n", "notebook.display(port=6006, height=1000) " ] }, { "cell_type": "markdown", "metadata": { "id": "za2GqzKiWY-R" }, "source": [ "" ] } ], "metadata": { "colab": { "collapsed_sections": [], "name": "tensorboard_in_notebooks.ipynb", "toc_visible": true }, "kernelspec": { "display_name": "Python 3", "name": "python3" } }, "nbformat": 4, "nbformat_minor": 0 }