{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "id": "wJcYs_ERTnnI" }, "outputs": [], "source": [ "##### Copyright 2021 The TensorFlow Authors." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "HMUDt0CiUJk9", "vscode": { "languageId": "python" } }, "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": "77z2OchJTk0l" }, "source": [ "# 迁移 TensorBoard:TensorFlow 的呈现工具包\n", "\n", "\n", " \n", " \n", " \n", " \n", "
在 TensorFlow.org 上查看 在 Google Colab 运行 在 Github 上查看源代码 下载笔记本
\n" ] }, { "cell_type": "markdown", "metadata": { "id": "hIo_p2FWFIRx" }, "source": [ "[TensorBoard](https://tensorflow.google.cn/tensorboard) 是一个内置工具,用于在 TensorFlow 中提供测量和呈现。可以在 TensorBoard 中跟踪和显示准确率和损失等常见的机器学习实验指标。TensorBoard 与 TensorFlow 1 和 2 代码兼容。\n", "\n", "在 TensorFlow 1 中,`tf.estimator.Estimator` 默认为 TensorBoard 保存摘要。相比之下,在 TensorFlow 2 中,可以使用 `tf.keras.callbacks.TensorBoard` 回调保存摘要。\n", "\n", "本指南首先演示了如何在 TensorFlow 1 中将 TensorBoard 与 Estimator 一起使用,然后演示了如何在 TensorFlow 2 中执行等效的过程。" ] }, { "cell_type": "markdown", "metadata": { "id": "f55c103999de" }, "source": [ "### 安装" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "X74yjOb-e18w", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "import tensorflow.compat.v1 as tf1\n", "import tensorflow as tf\n", "import tempfile\n", "import numpy as np\n", "import datetime\n", "%load_ext tensorboard" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "2r8r4d8FfMny", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "mnist = tf.keras.datasets.mnist # The MNIST dataset.\n", "\n", "(x_train, y_train),(x_test, y_test) = mnist.load_data()\n", "x_train, x_test = x_train / 255.0, x_test / 255.0" ] }, { "cell_type": "markdown", "metadata": { "id": "wrqBkG4RFLP_" }, "source": [ "### TensorFlow 1:TensorBoard 与 tf.estimator 一起使用\n", "\n", "在此 TensorFlow 1 示例中,您将实例化 `tf.estimator.DNNClassifier`,在 MNIST 数据集上对其进行训练和评估,并使用 TensorBoard 显示指标:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "upA8nuf3FEq5", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "%reload_ext tensorboard\n", "\n", "feature_columns = [tf1.feature_column.numeric_column(\"x\", shape=[28, 28])]\n", "\n", "config = tf1.estimator.RunConfig(save_summary_steps=1,\n", " save_checkpoints_steps=1)\n", "\n", "path = tempfile.mkdtemp()\n", "\n", "classifier = tf1.estimator.DNNClassifier(\n", " feature_columns=feature_columns,\n", " hidden_units=[256, 32],\n", " optimizer=tf1.train.AdamOptimizer(0.001),\n", " n_classes=10,\n", " dropout=0.1,\n", " model_dir=path,\n", " config = config\n", ")\n", "\n", "train_input_fn = tf1.estimator.inputs.numpy_input_fn(\n", " x={\"x\": x_train},\n", " y=y_train.astype(np.int32),\n", " num_epochs=10,\n", " batch_size=50,\n", " shuffle=True,\n", ")\n", "\n", "test_input_fn = tf1.estimator.inputs.numpy_input_fn(\n", " x={\"x\": x_test},\n", " y=y_test.astype(np.int32),\n", " num_epochs=10,\n", " shuffle=False\n", ")\n", "\n", "train_spec = tf1.estimator.TrainSpec(input_fn=train_input_fn, max_steps=10)\n", "eval_spec = tf1.estimator.EvalSpec(input_fn=test_input_fn,\n", " steps=10,\n", " throttle_secs=0)\n", "\n", "tf1.estimator.train_and_evaluate(estimator=classifier,\n", " train_spec=train_spec,\n", " eval_spec=eval_spec)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "EBqO7JbR8bh2", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "%tensorboard --logdir {classifier.model_dir}" ] }, { "cell_type": "markdown", "metadata": { "id": "GK8TK1CU88ns" }, "source": [ "" ] }, { "cell_type": "markdown", "metadata": { "id": "QvE_uxDJFUX-" }, "source": [ "### TensorFlow 2: TensorBoard 与 Keras 回调和 Model.fit 一起使用\n", "\n", "在此 TensorFlow 2 示例中,您将使用 `tf.keras.callbacks.TensorBoard` 回调创建和存储日志并训练模型。回调跟踪每个周期的准确率和损失。它会被传递给 `callbacks` 列表中的 `Model.fit`。" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "9FLBhT2BFX2H", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "%reload_ext tensorboard\n", "\n", "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", " ])\n", "\n", "model = create_model()\n", "model.compile(optimizer='adam',\n", " loss='sparse_categorical_crossentropy',\n", " metrics=['accuracy'],\n", " steps_per_execution=10)\n", "\n", "log_dir = tempfile.mkdtemp()\n", "tensorboard_callback = tf.keras.callbacks.TensorBoard(\n", " log_dir=log_dir,\n", " histogram_freq=1) # Enable histogram computation with each epoch.\n", "\n", "model.fit(x=x_train,\n", " y=y_train,\n", " epochs=10,\n", " validation_data=(x_test, y_test),\n", " callbacks=[tensorboard_callback])" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "ovPoLrCJ8t-R", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "%tensorboard --logdir {tensorboard_callback.log_dir}" ] }, { "cell_type": "markdown", "metadata": { "id": "Ip-IMGt_8xx9" }, "source": [ "\n" ] }, { "cell_type": "markdown", "metadata": { "id": "rQUS8nO9FZlH" }, "source": [ "# 后续步骤\n", "\n", "- 在[使用入门](https://tensorflow.google.cn/tensorboard/get_started)指南中详细了解 TensorBoard。\n", "- 对于较低级别的 API,请参阅 [tf.summary 迁移到 TensorFlow 2](https://tensorflow.google.cn/tensorboard/migrate) 指南。" ] } ], "metadata": { "colab": { "collapsed_sections": [], "name": "tensorboard.ipynb", "toc_visible": true }, "kernelspec": { "display_name": "Python 3", "name": "python3" } }, "nbformat": 4, "nbformat_minor": 0 }