{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "id": "djUvWu41mtXa" }, "outputs": [], "source": [ "##### Copyright 2019 The TensorFlow Authors." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "su2RaORHpReL", "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": "NztQK2uFpXT-" }, "source": [ "# TensorBoard Scalar:在 Keras 中记录训练指标\n", "\n", "\n", " \n", " \n", " \n", "
在 TensorFlow.org 上查看 在 Google Colab 中运行 在 Github 上查看源代码\n", "
" ] }, { "cell_type": "markdown", "metadata": { "id": "eDXRFe_qp5C3" }, "source": [ "## 文本特征向量\n", "\n", "机器学习总是涉及理解关键指标,例如损失,以及它们如何随着训练的进行而变化。 例如,这些指标可以帮助您了解模型是否[过拟合](https://en.wikipedia.org/wiki/Overfitting),或者是否不必要地训练了太长时间。 您可能需要比较不同训练中的这些指标,以帮助调试和改善模型。\n", "\n", "TensorBoard 的 **Time Series Dashboard** 允许您轻松地使用简单的 API 呈现这些指标。本教程提供了非常基本的示例,可帮助您在开发 Keras 模型时学习如何在 TensorBoard 中使用这些 API。您将学习如何使用 Keras TensorBoard 回调和 TensorFlow Summary API 来呈现默认和自定义标量。" ] }, { "cell_type": "markdown", "metadata": { "id": "dG-nnZK9qW9z" }, "source": [ "## 安装" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "3U5gdCw_nSG3", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "# Load the TensorBoard notebook extension.\n", "%load_ext tensorboard" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "1qIKtOBrqc9Y", "vscode": { "languageId": "python" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "TensorFlow version: 2.8.2\n" ] } ], "source": [ "from datetime import datetime\n", "from packaging import version\n", "\n", "import tensorflow as tf\n", "from tensorflow import keras\n", "from keras import backend as K\n", "\n", "import numpy as np\n", "\n", "print(\"TensorFlow version: \", tf.__version__)\n", "assert version.parse(tf.__version__).release[0] >= 2, \\\n", " \"This notebook requires TensorFlow 2.0 or above.\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "UbFM4dlnGB3S", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "# Clear any logs from previous runs\n", "!rm -rf ./logs/ " ] }, { "cell_type": "markdown", "metadata": { "id": "6YDAoNCN3ZNS" }, "source": [ "## 设置简单回归的数据\n", "\n", "您现在将使用 [Keras](https://tensorflow.google.cn/guide/keras) 计算回归,即找到对应数据集的最佳拟合。 (虽然使用神经网络和梯度下降[解决此类问题多此一举](https://stats.stackexchange.com/questions/160179/do-we-need-gradient-descent-to-find-the-coefficients-of-a-linear-regression-mode),但这却是一个非常容易理解的示例。)\n", "\n", "您将使用 TensorBoard 观察训练和测试**损失**在各个时期之间如何变化。希望您会看到训练集和测试集损失随着时间的流逝而减少,然后保持稳定。\n", "\n", "首先,大致沿线 *y = 0.5x + 2* 生成 1000 个数据点。将这些数据点分割为训练集和测试集。您希望神经网络能够学习这种关系。" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "j-ryO6OxnQH_", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "data_size = 1000\n", "# 80% of the data is for training.\n", "train_pct = 0.8\n", "\n", "train_size = int(data_size * train_pct)\n", "\n", "# Create some input data between -1 and 1 and randomize it.\n", "x = np.linspace(-1, 1, data_size)\n", "np.random.shuffle(x)\n", "\n", "# Generate the output data.\n", "# y = 0.5x + 2 + noise\n", "y = 0.5 * x + 2 + np.random.normal(0, 0.05, (data_size, ))\n", "\n", "# Split into test and train pairs.\n", "x_train, y_train = x[:train_size], y[:train_size]\n", "x_test, y_test = x[train_size:], y[train_size:]" ] }, { "cell_type": "markdown", "metadata": { "id": "Je59_8Ts3rq0" }, "source": [ "## 训练模型并记录损失\n", "\n", "您现在可以定义、训练和评估您的模型了。\n", "\n", "要在训练时记录*损失*标量,请执行以下操作:\n", "\n", "1. 创建 [Keras TensorBoard 回调](https://tensorflow.google.cn/api_docs/python/tf/keras/callbacks/TensorBoard)\n", "2. 指定日志目录\n", "3. 将 TensorBoard 回调传递给 Keras 的 [Model.fit()](https://tensorflow.google.cn/api_docs/python/tf/keras/models/Model#fit)。\n", "\n", "TensorBoard 从日志目录层次结构中读取日志数据。在此笔记本中,根日志目录为 `logs/scalars`,后缀为带时间戳的子目录。带时间戳的子目录支持在使用 TensorBoard 并在模型上迭代时轻松识别和选择训练运行。 " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "VmEQwCon3i7m", "vscode": { "languageId": "python" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Training ... With default parameters, this takes less than 10 seconds.\n", "Average test loss: 0.042797307365108284\n" ] } ], "source": [ "logdir = \"logs/scalars/\" + datetime.now().strftime(\"%Y%m%d-%H%M%S\")\n", "tensorboard_callback = keras.callbacks.TensorBoard(log_dir=logdir)\n", "\n", "model = keras.models.Sequential([\n", " keras.layers.Dense(16, input_dim=1),\n", " keras.layers.Dense(1),\n", "])\n", "\n", "model.compile(\n", " loss='mse', # keras.losses.mean_squared_error\n", " optimizer=keras.optimizers.SGD(learning_rate=0.2),\n", ")\n", "\n", "print(\"Training ... With default parameters, this takes less than 10 seconds.\")\n", "training_history = model.fit(\n", " x_train, # input\n", " y_train, # output\n", " batch_size=train_size,\n", " verbose=0, # Suppress chatty output; use Tensorboard instead\n", " epochs=100,\n", " validation_data=(x_test, y_test),\n", " callbacks=[tensorboard_callback],\n", ")\n", "\n", "print(\"Average test loss: \", np.average(training_history.history['loss']))" ] }, { "cell_type": "markdown", "metadata": { "id": "042k7GMERVkx" }, "source": [ "## 使用 TensorBoard 检查损失\n", "\n", "现在,启动 TensorBoard,指定上面使用的根日志目录。\n", "\n", "等待几秒钟,让 TensorBoard 的 UI 启动。 " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "6pck56gKReON", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "%tensorboard --logdir logs/scalars" ] }, { "cell_type": "markdown", "metadata": { "id": "QmQHlG10Kpu2" }, "source": [ "" ] }, { "cell_type": "markdown", "metadata": { "id": "ciSIRibhRi6N" }, "source": [ "您可能会看到 TensorBoard 显示消息“当前数据集没有活动的仪表板”。这是因为尚未保存初始日志记录数据。随着训练的进行,Keras 模型将开始记录数据。TensorBoard 将定期刷新并显示您的标量指标。如果您不耐烦,可以点击右上角的刷新箭头。\n", "\n", "当您观察训练进度时,请注意训练和验证损失如何快速下降,然后保持稳定。事实上,您可以在 25 个周期后停止训练,因为在那之后训练并没有太大改善。\n", "\n", "将鼠标悬停到计算图上可查看特定的数据点。您还可以尝试使用鼠标放大,或者选择其中一部分以查看更多详细信息。\n", "\n", "请注意左侧的“运行”选择器。“运行”代表一轮训练的一组日志,在这种情况下为 Model.fit() 的结果。随着时间的推移,开发者通常要运行很多次,因为他们需要试验和开发自己的模型。\n", "\n", "使用“运行”选择器选择特定运行,或者仅从训练或验证中进行选择。比较运行将帮助您评估哪个版本的代码可以更好地解决您的问题。\n" ] }, { "cell_type": "markdown", "metadata": { "id": "finK0GfYyefe" }, "source": [ "好的,TensorBoard 的损失图表明,训练和验证的损失都在持续下降,然后稳定下来。这意味着模型的指标可能非常好!现在看看模型在现实中的实际表现如何。\n", "\n", "给定输入数据 (60, 25, 2),行 *y = 0.5x + 2* 应产生 (32, 14.5, 3)。模型的结果是否一致?" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "EuiLgxQstt32", "vscode": { "languageId": "python" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[32.148884 ]\n", " [14.562463 ]\n", " [ 3.0056725]]\n" ] } ], "source": [ "print(model.predict([60, 25, 2]))\n", "# True values to compare predictions against: \n", "# [[32.0]\n", "# [14.5]\n", "# [ 3.0]]" ] }, { "cell_type": "markdown", "metadata": { "id": "bom4MdeewRKS" }, "source": [ "不错!" ] }, { "cell_type": "markdown", "metadata": { "id": "vvwGmJK9XWmh" }, "source": [ "## 记录自定义标量\n", "\n", "如果您想记录自定义值(例如[动态学习率](https://www.jeremyjordan.me/nn-learning-rate/)),该怎么办?为此,您需要使用 TensorFlow Summary API。\n", "\n", "重新训练回归模型并记录自定义学习率。具体步骤如下:\n", "\n", "1. 使用 `tf.summary.create_file_writer()` 创建文件编写器。\n", "2. 定义一个自定义学习率函数。这将传递给 Keras [LearningRateScheduler](https://tensorflow.google.cn/api_docs/python/tf/keras/callbacks/LearningRateScheduler) 回调。\n", "3. 在学习率函数内部,使用 `tf.summary.scalar()` 记录自定义学习率。\n", "4. 将 LearningRateScheduler 回调传递给 Model.fit()。\n", "\n", "通常,要记录自定义标量,您需要将 `tf.summary.scalar()` 与文件写入器一起使用。文件写入器负责将此运行的数据写入指定目录,并在您使用 `tf.summary.scalar()` 时隐式使用。" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "XB95ltRiXVXk", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "logdir = \"logs/scalars/\" + datetime.now().strftime(\"%Y%m%d-%H%M%S\")\n", "file_writer = tf.summary.create_file_writer(logdir + \"/metrics\")\n", "file_writer.set_as_default()\n", "\n", "def lr_schedule(epoch):\n", " \"\"\"\n", " Returns a custom learning rate that decreases as epochs progress.\n", " \"\"\"\n", " learning_rate = 0.2\n", " if epoch > 10:\n", " learning_rate = 0.02\n", " if epoch > 20:\n", " learning_rate = 0.01\n", " if epoch > 50:\n", " learning_rate = 0.005\n", "\n", " tf.summary.scalar('learning rate', data=learning_rate, step=epoch)\n", " return learning_rate\n", "\n", "lr_callback = keras.callbacks.LearningRateScheduler(lr_schedule)\n", "tensorboard_callback = keras.callbacks.TensorBoard(log_dir=logdir)\n", "\n", "model = keras.models.Sequential([\n", " keras.layers.Dense(16, input_dim=1),\n", " keras.layers.Dense(1),\n", "])\n", "\n", "model.compile(\n", " loss='mse', # keras.losses.mean_squared_error\n", " optimizer=keras.optimizers.SGD(),\n", ")\n", "\n", "training_history = model.fit(\n", " x_train, # input\n", " y_train, # output\n", " batch_size=train_size,\n", " verbose=0, # Suppress chatty output; use Tensorboard instead\n", " epochs=100,\n", " validation_data=(x_test, y_test),\n", " callbacks=[tensorboard_callback, lr_callback],\n", ")" ] }, { "cell_type": "markdown", "metadata": { "id": "pck8OQEjayDM" }, "source": [ "我们再看一下 TensorBoard。" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "0sjM2wXGa0mF", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "%tensorboard --logdir logs/scalars" ] }, { "cell_type": "markdown", "metadata": { "id": "GkIahGZKK9I7" }, "source": [ "" ] }, { "cell_type": "markdown", "metadata": { "id": "RRlUDnhlkN_q" }, "source": [ "使用左侧的“运行”选择器,请注意您有一个 `/metrics` 运行。选择此运行会显示“学习率”计算图,这样便可验证此运行期间学习率的进展。\n", "\n", "您还可以将此运行的训练和验证损失曲线与您之前的运行进行比较。您可能还注意到学习率计划返回离散值,具体取决于时期,但学习率图可能看起来很平滑TensorBoard 有一个平滑参数,您可能需要将其调低至零才能查看未平滑的值。\n" ] }, { "cell_type": "markdown", "metadata": { "id": "l0TTI16Nl0nk" }, "source": [ "这个模型怎么样?" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "97T4vT3QkQJH", "vscode": { "languageId": "python" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[31.958094 ]\n", " [14.482997 ]\n", " [ 2.9993598]]\n" ] } ], "source": [ "print(model.predict([60, 25, 2]))\n", "# True values to compare predictions against: \n", "# [[32.0]\n", "# [14.5]\n", "# [ 3.0]]" ] }, { "cell_type": "markdown", "metadata": { "id": "oxAVfW8lhZ0e" }, "source": [ "## 批量日志记录\n" ] }, { "cell_type": "markdown", "metadata": { "id": "p-ltiSuypLVE" }, "source": [ "首先,我们加载 MNIST 数据集,归一化数据并编写一个函数来创建一个用于将图像分成 10 类的简单 Keras 模型。" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "N2kbowJTpJWJ", "vscode": { "languageId": "python" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz\n", "11493376/11490434 [==============================] - 0s 0us/step\n", "11501568/11490434 [==============================] - 0s 0us/step\n" ] } ], "source": [ "mnist = tf.keras.datasets.mnist\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\n", "\n", "def create_model():\n", " return tf.keras.models.Sequential([\n", " tf.keras.layers.Flatten(input_shape=(28, 28)),\n", " tf.keras.layers.Dense(512, activation='relu'),\n", " tf.keras.layers.Dropout(0.2),\n", " tf.keras.layers.Dense(10, activation='softmax')\n", " ])" ] }, { "cell_type": "markdown", "metadata": { "id": "68pV5ZRe1iZ7" }, "source": [ "### 瞬时批次级日志记录" ] }, { "cell_type": "markdown", "metadata": { "id": "K_QYrBgkTsLH" }, "source": [ "以瞬时方式在批次级别记录指标可以向我们展示在每个周期内进行训练时批次间的波动程度,这对于调试而言非常有用。" ] }, { "cell_type": "markdown", "metadata": { "id": "6hXsbsXDqgvA" }, "source": [ "将摘要编写器设置到其他日志目录:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "7OTD7Vpg2DLv", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "log_dir = 'logs/batch_level/' + datetime.now().strftime(\"%Y%m%d-%H%M%S\") + '/train'\n", "train_writer = tf.summary.create_file_writer(log_dir)" ] }, { "cell_type": "markdown", "metadata": { "id": "YlVZY2VqrK9D" }, "source": [ "要启用批次级日志记录,应通过重写模型类定义中的 `train_step()` 来定义自定义 `tf.summary` 指标,并将其包含在摘要编写器上下文中。这可以简单地组合成子类化模型定义,也可以扩展以编辑我们之前的函数式 API 模型,如下所示:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "IGcNr1ZS1xXL", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "class MyModel(tf.keras.Model):\n", " def __init__(self, model):\n", " super().__init__()\n", " self.model = model\n", " \n", " def train_step(self, data):\n", " x, y = data\n", " with tf.GradientTape() as tape:\n", " y_pred = self.model(x, training=True)\n", " loss = self.compiled_loss(y, y_pred)\n", " mse = tf.keras.losses.mean_squared_error(y, K.max(y_pred, axis=-1))\n", " self.optimizer.minimize(loss, self.trainable_variables, tape=tape)\n", " with train_writer.as_default(step=self._train_counter):\n", " tf.summary.scalar('batch_loss', loss)\n", " tf.summary.scalar('batch_mse', mse)\n", " return self.compute_metrics(x, y, y_pred, None)\n", " \n", " def call(self, x):\n", " x = self.model(x)\n", " return x\n", "\n", "# Adds custom batch-level metrics to our previous Functional API model\n", "model = MyModel(create_model())\n", "model.compile(optimizer='adam',\n", " loss='sparse_categorical_crossentropy',\n", " metrics=['accuracy'])" ] }, { "cell_type": "markdown", "metadata": { "id": "8wqqNaXP2bLc" }, "source": [ "定义我们的 TensorBoard 回调以将周期级和批次级指标记录到我们的日志目录中,并使用我们选择的 `batch_size` 调用 `model.fit()`: " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "YXK-iE0e2UOE", "vscode": { "languageId": "python" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Epoch 1/5\n", "120/120 [==============================] - 5s 36ms/step - loss: 0.4379 - accuracy: 0.8788 - val_loss: 0.2041 - val_accuracy: 0.9430\n", "Epoch 2/5\n", "120/120 [==============================] - 4s 31ms/step - loss: 0.1875 - accuracy: 0.9471 - val_loss: 0.1462 - val_accuracy: 0.9591\n", "Epoch 3/5\n", "120/120 [==============================] - 3s 27ms/step - loss: 0.1355 - accuracy: 0.9613 - val_loss: 0.1170 - val_accuracy: 0.9670\n", "Epoch 4/5\n", "120/120 [==============================] - 3s 27ms/step - loss: 0.1058 - accuracy: 0.9694 - val_loss: 0.0954 - val_accuracy: 0.9723\n", "Epoch 5/5\n", "120/120 [==============================] - 3s 27ms/step - loss: 0.0872 - accuracy: 0.9752 - val_loss: 0.0843 - val_accuracy: 0.9749\n" ] }, { "data": { "text/plain": [ "" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir)\n", "\n", "model.fit(x=x_train, \n", " y=y_train,\n", " epochs=5,\n", " batch_size=500, \n", " validation_data=(x_test, y_test), \n", " callbacks=[tensorboard_callback])" ] }, { "cell_type": "markdown", "metadata": { "id": "SsxwF83h2kiM" }, "source": [ "以新的日志目录打开 TensorBoard 并查看周期级和批次级指标:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "XlcafPNY2oUW", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "%tensorboard --logdir logs/batch_level" ] }, { "cell_type": "markdown", "metadata": { "id": "ReO1LD-g2vgk" }, "source": [ "### 累积批次级日志记录" ] }, { "cell_type": "markdown", "metadata": { "id": "T0eE_yjt45TN" }, "source": [ "批次级日志记录也可累积式实现,对每个批次的指标与之前批次的指标求平均值,并在记录批次级指标时生成更加平滑的训练曲线。" ] }, { "cell_type": "markdown", "metadata": { "id": "He88QGuu25Vm" }, "source": [ "将摘要编写器设置到其他日志目录:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "hX3nsdqi28W1", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "log_dir = 'logs/batch_avg/' + datetime.now().strftime(\"%Y%m%d-%H%M%S\") + '/train'\n", "train_writer = tf.summary.create_file_writer(log_dir)" ] }, { "cell_type": "markdown", "metadata": { "id": "WHcpdSR6q5MY" }, "source": [ "创建可以按批次记录的有状态指标:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "0cAiVu_KjOVi", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "batch_loss = tf.keras.metrics.Mean('batch_loss', dtype=tf.float32)\n", "batch_accuracy = tf.keras.metrics.SparseCategoricalAccuracy('batch_accuracy')" ] }, { "cell_type": "markdown", "metadata": { "id": "f8ESFevo3Vjz" }, "source": [ "同样,请在被重写的 `train_step` 方法中添加自定义 `tf.summary` 指标。要使批次级日志记录成为累积式,请使用我们定义的有状态指标基于每个训练步骤的数据计算累积结果。" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "vQ_-46fpjUVl", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "class MyModel(tf.keras.Model):\n", " def __init__(self, model):\n", " super().__init__()\n", " self.model = model\n", " \n", " def train_step(self, data):\n", " x, y = data\n", " with tf.GradientTape() as tape:\n", " y_pred = self.model(x, training=True)\n", " loss = self.compiled_loss(y, y_pred)\n", " self.optimizer.minimize(loss, self.trainable_variables, tape=tape)\n", " batch_loss(loss)\n", " batch_accuracy(y, y_pred)\n", " with train_writer.as_default(step=self._train_counter):\n", " tf.summary.scalar('batch_loss', batch_loss.result())\n", " tf.summary.scalar('batch_accuracy', batch_accuracy.result())\n", " return self.compute_metrics(x, y, y_pred, None)\n", " \n", " def call(self, x):\n", " x = self.model(x)\n", " return x\n", "\n", "# Adds custom batch-level metrics to our previous Functional API model\n", "model = MyModel(create_model())\n", "model.compile(optimizer='adam',\n", " loss='sparse_categorical_crossentropy',\n", " metrics=['accuracy'])" ] }, { "cell_type": "markdown", "metadata": { "id": "NgtSX5E1uNhC" }, "source": [ "同样,定义我们的 TensorBoard 回调并使用我们选择的 `batch_size` 调用 `model.fit()`: " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "SGWYCUFhjztg", "vscode": { "languageId": "python" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Epoch 1/5\n", "120/120 [==============================] - 4s 27ms/step - loss: 0.4266 - accuracy: 0.8813 - val_loss: 0.2055 - val_accuracy: 0.9415\n", "Epoch 2/5\n", "120/120 [==============================] - 3s 26ms/step - loss: 0.1864 - accuracy: 0.9476 - val_loss: 0.1417 - val_accuracy: 0.9613\n", "Epoch 3/5\n", "120/120 [==============================] - 3s 27ms/step - loss: 0.1352 - accuracy: 0.9614 - val_loss: 0.1148 - val_accuracy: 0.9665\n", "Epoch 4/5\n", "120/120 [==============================] - 3s 26ms/step - loss: 0.1066 - accuracy: 0.9702 - val_loss: 0.0932 - val_accuracy: 0.9716\n", "Epoch 5/5\n", "120/120 [==============================] - 3s 27ms/step - loss: 0.0859 - accuracy: 0.9749 - val_loss: 0.0844 - val_accuracy: 0.9754\n" ] }, { "data": { "text/plain": [ "" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir)\n", "\n", "model.fit(x=x_train, \n", " y=y_train,\n", " epochs=5,\n", " batch_size=500, \n", " validation_data=(x_test, y_test), \n", " callbacks=[tensorboard_callback])" ] }, { "cell_type": "markdown", "metadata": { "id": "jSoDvPoDvAci" }, "source": [ "以新的日志目录打开 TensorBoard 并查看周期级和批次级指标:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "kYmYfTeSk7AD", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "%tensorboard --logdir logs/batch_avg" ] }, { "cell_type": "markdown", "metadata": { "id": "LXCePQi7_f50" }, "source": [ "就是这样!您现已知道如何在 TensorBoard 中为各种用例创建自定义训练指标了。" ] } ], "metadata": { "colab": { "collapsed_sections": [], "name": "scalars_and_keras.ipynb", "toc_visible": true }, "kernelspec": { "display_name": "Python 3", "name": "python3" } }, "nbformat": 4, "nbformat_minor": 0 }