{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "cFloNx163DCr" }, "source": [ "##### Copyright 2020 The TensorFlow Authors." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "iSdwTGPc3Hpj" }, "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": "BE2AKncl3QJZ" }, "source": [ "# 在 TensorBoard 中使用 Embedding Projector 呈现数据\n", "\n", "\n", " \n", " \n", " \n", " \n", "
在 TensorFlow.org 上查看 在 Google Colab 中运行 在 GitHub 上查看源代码 下载笔记本
" ] }, { "cell_type": "markdown", "metadata": { "id": "v4s3Sf2I3mJr" }, "source": [ "## 概述\n", "\n", "使用 **TensorBoard Embedding Projector**,您能够以图形表示高维嵌入向量。这有助于呈现、检查和理解您的嵌入向量层。\n", "\n", " \"Screenshot\n", "\n", "在本教程中,您将了解如何呈现这种经过训练的层。" ] }, { "cell_type": "markdown", "metadata": { "id": "6-0rhuaW9f2-" }, "source": [ "## 设置\n", "\n", "在本教程中,我们将使用 TensorBoard 呈现为分类电影评论数据而生成的嵌入向量层。" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "TjRkD3r3etuL" }, "outputs": [], "source": [ "try:\n", " # %tensorflow_version only exists in Colab.\n", " %tensorflow_version 2.x\n", "except Exception:\n", " pass\n", "\n", "%load_ext tensorboard" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "mh22cCoM8t7e" }, "outputs": [], "source": [ "import os\n", "import tensorflow as tf\n", "import tensorflow_datasets as tfds\n", "from tensorboard.plugins import projector\n" ] }, { "cell_type": "markdown", "metadata": { "id": "xlp6ZASQB5go" }, "source": [ "## IMDB 数据\n", "\n", "我们将使用 25,000 条 IMDB 电影评论组成的数据集,每条评论都具有情感标签(正面/负面)。每条评论都已经过预处理,并被编码为单词索引(整数)序列。为方便起见,单词将基于在数据集中出现的总频率建立索引。因此,以整数“3”为例,它将编码在所有评论中出现频率第 3 高的单词。这样可以快速筛选运算,例如:“仅考虑前 10,000 个最常用单词,但排除前 20 个最常用单词”。\n", "\n", "按照惯例,“0”不代表特定单词,而是用于编码任何未知的单词。在本教程的后面部分中,我们将在呈现中移除“0”对应的行。\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "s0Yiw05gIgqS" }, "outputs": [], "source": [ "(train_data, test_data), info = tfds.load(\n", " \"imdb_reviews/subwords8k\",\n", " split=(tfds.Split.TRAIN, tfds.Split.TEST),\n", " with_info=True,\n", " as_supervised=True,\n", ")\n", "encoder = info.features[\"text\"].encoder\n", "\n", "# Shuffle and pad the data.\n", "train_batches = train_data.shuffle(1000).padded_batch(\n", " 10, padded_shapes=((None,), ())\n", ")\n", "test_batches = test_data.shuffle(1000).padded_batch(\n", " 10, padded_shapes=((None,), ())\n", ")\n", "train_batch, train_labels = next(iter(train_batches))\n" ] }, { "cell_type": "markdown", "metadata": { "id": "RpvPVCwO7bDj" }, "source": [ "# Keras 嵌入向量层\n", "\n", "[Keras 嵌入向量层](https://keras.io/layers/embeddings/)可用于训练词汇表中每个单词的嵌入向量。每个单词(在这种情况下为子单词)将与模型将训练的 16 维向量(或嵌入向量)相关联。\n", "\n", "请参阅[本教程](https://tensorflow.google.cn/tutorials/text/word_embeddings?hl=en),详细了解单词嵌入向量。" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "id": "Fgoq5haqw8Z5" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2500/2500 [==============================] - 13s 5ms/step - loss: 0.5330 - accuracy: 0.6769 - val_loss: 0.4043 - val_accuracy: 0.7800\n" ] } ], "source": [ "# Create an embedding layer.\n", "embedding_dim = 16\n", "embedding = tf.keras.layers.Embedding(encoder.vocab_size, embedding_dim)\n", "# Configure the embedding layer as part of a keras model.\n", "model = tf.keras.Sequential(\n", " [\n", " embedding, # The embedding layer should be the first layer in a model.\n", " tf.keras.layers.GlobalAveragePooling1D(),\n", " tf.keras.layers.Dense(16, activation=\"relu\"),\n", " tf.keras.layers.Dense(1),\n", " ]\n", ")\n", "\n", "# Compile model.\n", "model.compile(\n", " optimizer=\"adam\",\n", " loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),\n", " metrics=[\"accuracy\"],\n", ")\n", "\n", "# Train model for one epoch.\n", "history = model.fit(\n", " train_batches, epochs=1, validation_data=test_batches, validation_steps=20\n", ")" ] }, { "cell_type": "markdown", "metadata": { "id": "s9HmC29hdMnH" }, "source": [ "## 为 TensorBoard 保存数据\n", "\n", "TensorBoard 从 TensorFlow 项目的日志中读取张量和元数据。日志目录的路径使用下面的 `log_dir` 指定。对于本教程,我们将使用 `/logs/imdb-example/`。\n", "\n", "要将数据加载到 TensorBoard 中,我们需要将训练检查点连同可以呈现模型中所关注特定层的元数据保存到该目录中。 " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "Pi8_SCYRdn9x" }, "outputs": [], "source": [ "# Set up a logs directory, so Tensorboard knows where to look for files.\n", "log_dir='/logs/imdb-example/'\n", "if not os.path.exists(log_dir):\n", " os.makedirs(log_dir)\n", "\n", "# Save Labels separately on a line-by-line manner.\n", "with open(os.path.join(log_dir, 'metadata.tsv'), \"w\") as f:\n", " for subwords in encoder.subwords:\n", " f.write(\"{}\\n\".format(subwords))\n", " # Fill in the rest of the labels with \"unknown\".\n", " for unknown in range(1, encoder.vocab_size - len(encoder.subwords)):\n", " f.write(\"unknown #{}\\n\".format(unknown))\n", "\n", "\n", "# Save the weights we want to analyze as a variable. Note that the first\n", "# value represents any unknown word, which is not in the metadata, here\n", "# we will remove this value.\n", "weights = tf.Variable(model.layers[0].get_weights()[0][1:])\n", "# Create a checkpoint from embedding, the filename and key are the\n", "# name of the tensor.\n", "checkpoint = tf.train.Checkpoint(embedding=weights)\n", "checkpoint.save(os.path.join(log_dir, \"embedding.ckpt\"))\n", "\n", "# Set up config.\n", "config = projector.ProjectorConfig()\n", "embedding = config.embeddings.add()\n", "# The name of the tensor will be suffixed by `/.ATTRIBUTES/VARIABLE_VALUE`.\n", "embedding.tensor_name = \"embedding/.ATTRIBUTES/VARIABLE_VALUE\"\n", "embedding.metadata_path = 'metadata.tsv'\n", "projector.visualize_embeddings(log_dir, config)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "PtL_KzYMBIzP" }, "outputs": [], "source": [ "# Now run tensorboard against on log data we just saved.\n", "%tensorboard --logdir /logs/imdb-example/" ] }, { "cell_type": "markdown", "metadata": { "id": "YtzW8mr_wmbD" }, "source": [ "" ] }, { "cell_type": "markdown", "metadata": { "id": "MG4hcUzQQoWA" }, "source": [ "## 分析\n", "\n", "TensorBoard Projector 是一个用于解释和呈现嵌入向量的出色工具。信息中心允许用户搜索特定术语,并突出显示嵌入向量(低维)空间中彼此相邻的单词。从本例中我们可以看到, Wes **Anderson** 和 Alfred **Hitchcock** 都是较为中性的术语,但它们在不同的上下文中被引用。\n", "\n", "\n", "\n", "在此空间中,Hitchcock 更接近于 `nightmare` 之类的单词,这可能是因为他被称为“悬念大师”,而 Anderson 更接近于 `heart` 这个单词,这与他无比细致和温暖的风格相吻合。\n", "\n", "" ] } ], "metadata": { "colab": { "collapsed_sections": [], "name": "tensorboard_projector_plugin.ipynb", "toc_visible": true }, "kernelspec": { "display_name": "Python 3", "name": "python3" } }, "nbformat": 4, "nbformat_minor": 0 }