<commit_before>{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "tensorboard_dev_summit_2019.ipynb",
      "version": "0.3.2",
      "provenance": [],
      "collapsed_sections": [],
      "toc_visible": true
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    }
  },
  "cells": [
    {
      "metadata": {
        "id": "2kXAFPLsEKZm",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "##### Copyright 2019 The TensorFlow Authors.\n"
      ]
    },
    {
      "metadata": {
        "id": "4eFFg1vlEJGY",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "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."
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "Zr1JuYsaoTDE",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "# What's new with TensorBoard?\n",
        "\n",
        "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/examples/blob/master/community/en/tensorboard/tensorboard_dev_summit_2019.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://github.com/tensorflow/tensorboard/examples/blob/master/community/en/tensorboard/tensorboard_dev_summit_2019.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n",
        "  </td>\n",
        "</table>"
      ]
    },
    {
      "metadata": {
        "id": "diTH3H5L6pcB",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "This is a notebook from the TensorBoard talk at the TensorFlow Dev Summit 2019, which can be found [here](https://www.youtube.com/watch?v=xM8sO33x_OU). More detailed documentation about these features can be found at [tensorflow.org/tensorboard](https://www.tensorflow.org/tensorboard)\n",
        "\n",
        "This notebook was slightly modified after the demo to remove account-specific data."
      ]
    },
    {
      "metadata": {
        "id": "h8yQwDlIz4My",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "!pip install -qU tensorflow==2.0.0a0\n",
        "\n",
        "# Load the TensorBoard notebook extension\n",
        "%load_ext tensorboard.notebook "
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "XaacEJm60MUt",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "# Clear any logs from previous runs\n",
        "!rm -rf ./logs/ "
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "ObvQlJAH6Aln",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "import tensorflow as tf\n",
        "import datetime"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "OEPfW_CIoaaI",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "### A dataset you've never seen before. FashionMNIST"
      ]
    },
    {
      "metadata": {
        "id": "UmLnA3h282gS",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "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"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "s9qqxNNOowFB",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "### Keras Sequential model trained with `.fit()`"
      ]
    },
    {
      "metadata": {
        "id": "za6m7-M0-hOG",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "def train_test_model(run_dir, hparams):\n",
        "\n",
        "  model = tf.keras.models.Sequential([\n",
        "    tf.keras.layers.Flatten(),\n",
        "    tf.keras.layers.Dense(hparams['num_units'], activation=tf.nn.relu),\n",
        "    tf.keras.layers.Dropout(hparams['dropout_rate']),\n",
        "    tf.keras.layers.Dense(10, activation=tf.nn.softmax)\n",
        "  ])\n",
        "\n",
        "  model.compile(optimizer= hparams['optimizer'],\n",
        "                loss='sparse_categorical_crossentropy',\n",
        "                metrics=['accuracy'])\n",
        "\n",
        "  model.fit(x_train, y_train, \n",
        "            validation_data=(x_test, y_test), \n",
        "            epochs=3, \n",
        "            callbacks=[tf.keras.callbacks.TensorBoard(run_dir + \"/keras\")])\n",
        " \n",
        "  scores = model.evaluate(x_test, y_test)\n",
        "  return scores"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "AHiPRhtj_JNa",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "train_test_model(\"logs/sample\", {'num_units' : 16, 'dropout_rate' : 0.1, 'optimizer' : 'adam'})"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "YYwlqWbXo5tc",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "### Alright let's download this data, install TensorBoard, and open it locally. Or..."
      ]
    },
    {
      "metadata": {
        "id": "eGEC-gRWDJux",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "%tensorboard --logdir logs/sample"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "oIgtqsiZ8Ktv",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "Note that train and validation now appear as separate runs so you can compare them on the same charts. \n",
        "\n",
        "In the Graphs dashboard, click on \"keras\" in the \"Tag\" dropdown to view the Keras conceptual graph.\n",
        "\n",
        "Other useful APIs for working with TensorBoard in notebooks:"
      ]
    },
    {
      "metadata": {
        "id": "4Qq2uUd0DQcA",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "# from tensorboard import notebook\n",
        "# notebook.display(height=1000)\n",
        "# notebook.list()"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "6IPoyD1MZyvM",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "# Hyperparameter Tuning"
      ]
    },
    {
      "metadata": {
        "id": "UpfFgNco8v8E",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "Today, you can try out different hyperparameters by encoding them in the run names and then comparing them in TensorBoard. This is not ideal, so let's see if we can do something better. Note that the experience below will change over time."
      ]
    },
    {
      "metadata": {
        "id": "R3xZXCasv3a7",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "<img src=\"https://user-images.githubusercontent.com/2601900/53466264-2535ac00-3a06-11e9-8010-ce2f448a0758.png\" alt=\"Sad Hparams\" width=\"70%\"/>"
      ]
    },
    {
      "metadata": {
        "id": "aKe7HKRNztF_",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "### Let's try to do something better\n",
        "\n",
        "#### Preview APIs that will change:"
      ]
    },
    {
      "metadata": {
        "id": "8Nb4HvuCb2Nj",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "from tensorboard.plugins.hparams import api_pb2\n",
        "from tensorboard.plugins.hparams import summary as hparams_summary\n",
        "from google.protobuf import struct_pb2"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "qVuWG8NBzysZ",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "### We'll try a few modifications to our very simple model"
      ]
    },
    {
      "metadata": {
        "id": "D8MuCY0uZ2xO",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "num_units_list = [16, 32] # Number of units in the dense layer\n",
        "dropout_rate_list = [0.1, 0.2] # Dropout rate\n",
        "optimizer_list = ['adam']"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "QQsCNqTmz_KK",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "### Log a summary of which hyperparameters and metrics we care about"
      ]
    },
    {
      "metadata": {
        "id": "fBTWqmXNaERV",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "def create_experiment_summary(num_units_list, dropout_rate_list, optimizer_list):\n",
        "  num_units_list_val = struct_pb2.ListValue()\n",
        "  num_units_list_val.extend(num_units_list)\n",
        "  dropout_rate_list_val = struct_pb2.ListValue()\n",
        "  dropout_rate_list_val.extend(dropout_rate_list)\n",
        "  optimizer_list_val = struct_pb2.ListValue()\n",
        "  optimizer_list_val.extend(optimizer_list)\n",
        "  return hparams_summary.experiment_pb(\n",
        "      # List our hyperparameters\n",
        "      hparam_infos=[\n",
        "          api_pb2.HParamInfo(name='num_units',\n",
        "                             display_name='Number of units',\n",
        "                             type=api_pb2.DATA_TYPE_FLOAT64,\n",
        "                             domain_discrete=num_units_list_val),\n",
        "          api_pb2.HParamInfo(name='dropout_rate',\n",
        "                             display_name='Dropout rate',\n",
        "                             type=api_pb2.DATA_TYPE_FLOAT64,\n",
        "                             domain_discrete=dropout_rate_list_val),\n",
        "          api_pb2.HParamInfo(name='optimizer',\n",
        "                             display_name='Optimizer',\n",
        "                             type=api_pb2.DATA_TYPE_STRING,\n",
        "                             domain_discrete=optimizer_list_val)\n",
        "      ],\n",
        "      # List our metrics\n",
        "      metric_infos=[\n",
        "          api_pb2.MetricInfo(\n",
        "              name=api_pb2.MetricName(\n",
        "                  tag='accuracy'),\n",
        "              display_name='Accuracy'),\n",
        "      ]\n",
        "  )\n",
        "\n",
        "exp_summary = create_experiment_summary(num_units_list, dropout_rate_list, optimizer_list)\n",
        "root_logdir_writer = tf.summary.create_file_writer(\"logs/hparam_tuning\")\n",
        "with root_logdir_writer.as_default():\n",
        "  tf.summary.import_event(tf.compat.v1.Event(summary=exp_summary).SerializeToString())"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "pzSyvfyZ0IQ6",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "### Wrap our existing training code to log when each run has finished, along with its metrics"
      ]
    },
    {
      "metadata": {
        "id": "UNqOHUnVasDz",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "def run(run_dir, hparams):\n",
        "  writer = tf.summary.create_file_writer(run_dir)\n",
        "  summary_start = hparams_summary.session_start_pb(hparams=hparams)\n",
        "\n",
        "  with writer.as_default():\n",
        "    tf.summary.import_event(tf.compat.v1.Event(summary=summary_start).SerializeToString())\n",
        "    loss, accuracy = train_test_model(run_dir, hparams)\n",
        "    \n",
        "    tf.summary.scalar('accuracy', accuracy, step=0, description=\"The accuracy\")\n",
        "    summary_end = hparams_summary.session_end_pb(api_pb2.STATUS_SUCCESS)\n",
        "    tf.summary.import_event(tf.compat.v1.Event(summary=summary_end).SerializeToString())"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "y0OTtS3j0eT_",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "### Try all combinations of hyperparameters as separate runs"
      ]
    },
    {
      "metadata": {
        "id": "qLUZSP4wcTwZ",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "%tensorboard --logdir logs/hparam_tuning"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "p38E9rOubmdw",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "session_num = 0\n",
        "\n",
        "for num_units in num_units_list:\n",
        "  for dropout_rate in dropout_rate_list:\n",
        "    for optimizer in optimizer_list:\n",
        "      hparams = {'num_units': num_units, 'dropout_rate': dropout_rate, 'optimizer': optimizer}\n",
        "      print('--- Running training session %d' % (session_num + 1))\n",
        "      print(hparams)\n",
        "      run_name = \"run-%d\" % session_num\n",
        "      run(\"logs/hparam_tuning/\" + run_name, hparams)\n",
        "      session_num += 1"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "jjs5_qTK_MTi",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "Refresh TensorBoard and look at the HParams dashboard for various visualizations"
      ]
    },
    {
      "metadata": {
        "id": "rcOrkDHU05XO",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "### Testing more combinations will take a while, let's cheat and look at the end result"
      ]
    },
    {
      "metadata": {
        "id": "RWNbag4H9ZOp",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "# The Dev Summit demo showed using logs directly from Google Drive, such as \n",
        "# the following:\n",
        "\n",
        "# from google.colab import drive\n",
        "# drive.mount('/content/gdrive')\n",
        "\n",
        "# %tensorboard --logdir /content/gdrive/My\\ Drive/DevSummit/hparams_demo\n",
        "\n",
        "# For this notebook, download the logs directly (but you can place them in \n",
        "# Google Drive to replicate the above experience)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "RnEqRUM39Rqw",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "%%bash\n",
        "wget -q 'https://storage.googleapis.com/download.tensorflow.org/tensorboard/hparams_demo_logs.zip'\n",
        "unzip -q hparams_demo_logs.zip -d logs/hparam_demo"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "H0dmFaIm9S6v",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "%tensorboard --logdir logs/hparam_demo"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "0z7DLT4G1UFT",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "# Summary\n",
        "\n",
        "### We've looked at:\n",
        "### - TensorBoard in Colab\n",
        "### - Easier comparison of train and validation runs\n",
        "### - Keras conceptual graph visualization\n",
        "### - Hyperparameter tuning with the HParams dashboard\n",
        "\n",
        "\\\n",
        "\n",
        "### Documentation available at [tensorflow.org/tensorboard](https://tensorflow.org/tensorboard)"
      ]
    }
  ]
}<commit_msg>Formatting<commit_after>{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "tf_dev_summit_2019.ipynb",
      "version": "0.3.2",
      "provenance": [],
      "collapsed_sections": [],
      "toc_visible": true
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    }
  },
  "cells": [
    {
      "metadata": {
        "id": "2kXAFPLsEKZm",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "##### Copyright 2019 The TensorFlow Authors.\n"
      ]
    },
    {
      "metadata": {
        "id": "4eFFg1vlEJGY",
        "colab_type": "code",
        "colab": {},
        "cellView": "form"
      },
      "cell_type": "code",
      "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."
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "Zr1JuYsaoTDE",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "# What's new with TensorBoard?\n",
        "\n",
        "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/examples/blob/master/community/en/tensorboard/tf_dev_summit_2019.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://github.com/tensorflow/tensorboard/examples/blob/master/community/en/tensorboard/tf_dev_summit_2019.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n",
        "  </td>\n",
        "</table>"
      ]
    },
    {
      "metadata": {
        "id": "diTH3H5L6pcB",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "This is a notebook from the TensorBoard talk at the TensorFlow Dev Summit 2019, which can be found [here](https://www.youtube.com/watch?v=xM8sO33x_OU). More detailed documentation about these features can be found at [tensorflow.org/tensorboard](https://www.tensorflow.org/tensorboard)\n",
        "\n",
        "This notebook was slightly modified after the demo to remove account-specific data."
      ]
    },
    {
      "metadata": {
        "id": "h8yQwDlIz4My",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "!pip install -qU tensorflow==2.0.0a0\n",
        "\n",
        "# Load the TensorBoard notebook extension\n",
        "%load_ext tensorboard.notebook "
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "XaacEJm60MUt",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "# Clear any logs from previous runs\n",
        "!rm -rf ./logs/ "
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "ObvQlJAH6Aln",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "import tensorflow as tf\n",
        "import datetime"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "OEPfW_CIoaaI",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "### A dataset you've never seen before. FashionMNIST"
      ]
    },
    {
      "metadata": {
        "id": "UmLnA3h282gS",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "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"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "s9qqxNNOowFB",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "### Keras Sequential model trained with `.fit()`"
      ]
    },
    {
      "metadata": {
        "id": "za6m7-M0-hOG",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "def train_test_model(run_dir, hparams):\n",
        "\n",
        "  model = tf.keras.models.Sequential([\n",
        "    tf.keras.layers.Flatten(),\n",
        "    tf.keras.layers.Dense(hparams['num_units'], activation=tf.nn.relu),\n",
        "    tf.keras.layers.Dropout(hparams['dropout_rate']),\n",
        "    tf.keras.layers.Dense(10, activation=tf.nn.softmax)\n",
        "  ])\n",
        "\n",
        "  model.compile(optimizer= hparams['optimizer'],\n",
        "                loss='sparse_categorical_crossentropy',\n",
        "                metrics=['accuracy'])\n",
        "\n",
        "  model.fit(x_train, y_train, \n",
        "            validation_data=(x_test, y_test), \n",
        "            epochs=3, \n",
        "            callbacks=[tf.keras.callbacks.TensorBoard(run_dir + \"/keras\")])\n",
        " \n",
        "  scores = model.evaluate(x_test, y_test)\n",
        "  return scores"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "AHiPRhtj_JNa",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "train_test_model(\"logs/sample\", {'num_units' : 16, 'dropout_rate' : 0.1, 'optimizer' : 'adam'})"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "YYwlqWbXo5tc",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "### Alright let's download this data, install TensorBoard, and open it locally. Or..."
      ]
    },
    {
      "metadata": {
        "id": "eGEC-gRWDJux",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "%tensorboard --logdir logs/sample"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "oIgtqsiZ8Ktv",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "Note that train and validation now appear as separate runs so you can compare them on the same charts. \n",
        "\n",
        "In the Graphs dashboard, click on \"keras\" in the \"Tag\" dropdown to view the Keras conceptual graph.\n",
        "\n",
        "Other useful APIs for working with TensorBoard in notebooks:"
      ]
    },
    {
      "metadata": {
        "id": "4Qq2uUd0DQcA",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "# from tensorboard import notebook\n",
        "# notebook.display(height=1000)\n",
        "# notebook.list()"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "6IPoyD1MZyvM",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "# Hyperparameter Tuning"
      ]
    },
    {
      "metadata": {
        "id": "UpfFgNco8v8E",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "Today, you can try out different hyperparameters by encoding them in the run names and then comparing them in TensorBoard. This is not ideal, so let's see if we can do something better. Note that the experience below will change over time."
      ]
    },
    {
      "metadata": {
        "id": "R3xZXCasv3a7",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "<img src=\"https://user-images.githubusercontent.com/2601900/53466264-2535ac00-3a06-11e9-8010-ce2f448a0758.png\" alt=\"Sad Hparams\" width=\"70%\"/>"
      ]
    },
    {
      "metadata": {
        "id": "aKe7HKRNztF_",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "### Let's try to do something better\n",
        "\n",
        "#### Preview APIs that will change:"
      ]
    },
    {
      "metadata": {
        "id": "8Nb4HvuCb2Nj",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "from tensorboard.plugins.hparams import api_pb2\n",
        "from tensorboard.plugins.hparams import summary as hparams_summary\n",
        "from google.protobuf import struct_pb2"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "qVuWG8NBzysZ",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "### We'll try a few modifications to our very simple model"
      ]
    },
    {
      "metadata": {
        "id": "D8MuCY0uZ2xO",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "num_units_list = [16, 32] # Number of units in the dense layer\n",
        "dropout_rate_list = [0.1, 0.2] # Dropout rate\n",
        "optimizer_list = ['adam']"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "QQsCNqTmz_KK",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "### Log a summary of which hyperparameters and metrics we care about"
      ]
    },
    {
      "metadata": {
        "id": "fBTWqmXNaERV",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "def create_experiment_summary(num_units_list, dropout_rate_list, optimizer_list):\n",
        "  num_units_list_val = struct_pb2.ListValue()\n",
        "  num_units_list_val.extend(num_units_list)\n",
        "  dropout_rate_list_val = struct_pb2.ListValue()\n",
        "  dropout_rate_list_val.extend(dropout_rate_list)\n",
        "  optimizer_list_val = struct_pb2.ListValue()\n",
        "  optimizer_list_val.extend(optimizer_list)\n",
        "  return hparams_summary.experiment_pb(\n",
        "      # List our hyperparameters\n",
        "      hparam_infos=[\n",
        "          api_pb2.HParamInfo(name='num_units',\n",
        "                             display_name='Number of units',\n",
        "                             type=api_pb2.DATA_TYPE_FLOAT64,\n",
        "                             domain_discrete=num_units_list_val),\n",
        "          api_pb2.HParamInfo(name='dropout_rate',\n",
        "                             display_name='Dropout rate',\n",
        "                             type=api_pb2.DATA_TYPE_FLOAT64,\n",
        "                             domain_discrete=dropout_rate_list_val),\n",
        "          api_pb2.HParamInfo(name='optimizer',\n",
        "                             display_name='Optimizer',\n",
        "                             type=api_pb2.DATA_TYPE_STRING,\n",
        "                             domain_discrete=optimizer_list_val)\n",
        "      ],\n",
        "      # List our metrics\n",
        "      metric_infos=[\n",
        "          api_pb2.MetricInfo(\n",
        "              name=api_pb2.MetricName(\n",
        "                  tag='accuracy'),\n",
        "              display_name='Accuracy'),\n",
        "      ]\n",
        "  )\n",
        "\n",
        "exp_summary = create_experiment_summary(num_units_list, dropout_rate_list, optimizer_list)\n",
        "root_logdir_writer = tf.summary.create_file_writer(\"logs/hparam_tuning\")\n",
        "with root_logdir_writer.as_default():\n",
        "  tf.summary.import_event(tf.compat.v1.Event(summary=exp_summary).SerializeToString())"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "pzSyvfyZ0IQ6",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "### Wrap our existing training code to log when each run has finished, along with its metrics"
      ]
    },
    {
      "metadata": {
        "id": "UNqOHUnVasDz",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "def run(run_dir, hparams):\n",
        "  writer = tf.summary.create_file_writer(run_dir)\n",
        "  summary_start = hparams_summary.session_start_pb(hparams=hparams)\n",
        "\n",
        "  with writer.as_default():\n",
        "    tf.summary.import_event(tf.compat.v1.Event(summary=summary_start).SerializeToString())\n",
        "    loss, accuracy = train_test_model(run_dir, hparams)\n",
        "    \n",
        "    tf.summary.scalar('accuracy', accuracy, step=0, description=\"The accuracy\")\n",
        "    summary_end = hparams_summary.session_end_pb(api_pb2.STATUS_SUCCESS)\n",
        "    tf.summary.import_event(tf.compat.v1.Event(summary=summary_end).SerializeToString())"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "y0OTtS3j0eT_",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "### Try all combinations of hyperparameters as separate runs"
      ]
    },
    {
      "metadata": {
        "id": "qLUZSP4wcTwZ",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "%tensorboard --logdir logs/hparam_tuning"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "p38E9rOubmdw",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "session_num = 0\n",
        "\n",
        "for num_units in num_units_list:\n",
        "  for dropout_rate in dropout_rate_list:\n",
        "    for optimizer in optimizer_list:\n",
        "      hparams = {'num_units': num_units, 'dropout_rate': dropout_rate, 'optimizer': optimizer}\n",
        "      print('--- Running training session %d' % (session_num + 1))\n",
        "      print(hparams)\n",
        "      run_name = \"run-%d\" % session_num\n",
        "      run(\"logs/hparam_tuning/\" + run_name, hparams)\n",
        "      session_num += 1"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "jjs5_qTK_MTi",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "Refresh TensorBoard and look at the HParams dashboard for various visualizations"
      ]
    },
    {
      "metadata": {
        "id": "rcOrkDHU05XO",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "### Testing more combinations will take a while, let's cheat and look at the end result"
      ]
    },
    {
      "metadata": {
        "id": "RWNbag4H9ZOp",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "# The Dev Summit demo showed using logs directly from Google Drive, such as \n",
        "# the following:\n",
        "\n",
        "# from google.colab import drive\n",
        "# drive.mount('/content/gdrive')\n",
        "\n",
        "# %tensorboard --logdir /content/gdrive/My\\ Drive/DevSummit/hparams_demo\n",
        "\n",
        "# For this notebook, download the logs directly (but you can place them in \n",
        "# Google Drive to replicate the above experience)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "RnEqRUM39Rqw",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "%%bash\n",
        "wget -q 'https://storage.googleapis.com/download.tensorflow.org/tensorboard/hparams_demo_logs.zip'\n",
        "unzip -q hparams_demo_logs.zip -d logs/hparam_demo"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "H0dmFaIm9S6v",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "%tensorboard --logdir logs/hparam_demo"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "0z7DLT4G1UFT",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "# Summary\n",
        "\n",
        "We've looked at:\n",
        "- TensorBoard in Colab\n",
        "- Easier comparison of train and validation runs\n",
        "- Keras conceptual graph visualization\n",
        "- Hyperparameter tuning with the HParams dashboard\n",
        "\n",
        "Read the TensorBoard documentation at: [tensorflow.org/tensorboard](https://tensorflow.org/tensorboard)"
      ]
    }
  ]
}
{'fraction_non_alphanumeric': 0.1678771588699531, 'fraction_numerical': 0.012352739334324602, 'mean_word_length': 1.821085746551585, 'pattern_counts': {'":': 495, '<': 29, '<?xml version=': 0, '>': 29, 'https://': 20, 'lorem ipsum': 0, 'www.': 10, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 24, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '972135', 'n_tokens_mistral': 12115, 'n_tokens_neox': 11752, 'n_words': 2164}