{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "id": "b518b04cbfe0" }, "outputs": [], "source": [ "##### Copyright 2020 The TensorFlow Authors." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "906e07f6e562", "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": "6e083398b477" }, "source": [ "# 使用预处理层" ] }, { "cell_type": "markdown", "metadata": { "id": "64010bd23c2e" }, "source": [ "\n", " \n", " \n", " \n", " \n", "
在 TensorFlow.org 上查看\n", "在 Google Colab 中运行 在 GitHub 上查看源代码\n", " 下载笔记本\n", "
" ] }, { "cell_type": "markdown", "metadata": { "id": "b1d403f04693" }, "source": [ "## Keras 预处理\n", "\n", "Keras 预处理层 API 可供开发者构建 Keras 原生输入处理流水线。这些输入处理流水线可在非 Keras 工作流中用作独立预处理代码,直接与 Keras 模型结合,并作为 Keras SavedModel 的一部分导出。\n", "\n", "借助 Keras 预处理层,您可以构建和导出真正端到端的模型:接受原始图像或原始结构化数据作为输入的模型;自行处理特征归一化或特征值索引的模型。" ] }, { "cell_type": "markdown", "metadata": { "id": "313360fa9024" }, "source": [ "## 可用预处理\n", "\n", "### 文本预处理\n", "\n", "- `tf.keras.layers.TextVectorization`:将原始字符串转换为可由 `Embedding` 层或 `Dense` 层读取的编码表示法。\n", "\n", "### 数值特征预处理\n", "\n", "- `tf.keras.layers.Normalization`:对输入特征执行逐特征归一化。\n", "- `tf.keras.layers.Discretization`:将连续数值特征转换为整数分类特征。\n", "\n", "### 分类特征预处理\n", "\n", "- `tf.keras.layers.CategoryEncoding`:将整数分类特征转换为独热、多热或计数密集表示法。\n", "- `tf.keras.layers.Hashing`:执行分类特征哈希,也称为“哈希技巧”(hashing trick)。\n", "- `tf.keras.layers.StringLookup`:将字符串分类值转换为可由 `Embedding` 层或 `Dense` 层读取的编码表示法。\n", "- `tf.keras.layers.IntegerLookup`:将整数分类值转换为可由 `Embedding` 层或 `Dense` 层读取的编码表示法。\n", "\n", "### 图像预处理\n", "\n", "这些层用于标准化图像模型的输入。\n", "\n", "- `tf.keras.layers.Resizing`:将一批图像的大小调整为目标大小。\n", "- `tf.keras.layers.Rescaling`:重新缩放和偏移一批图像的值(例如,从 `[0, 255]` 范围内的输入变为 `[0, 1]` 范围内的输入)。\n", "- `tf.keras.layers.CenterCrop`:返回一批图像的中心裁剪。\n", "\n", "### 图像数据增强\n", "\n", "以下层会对一批图像应用随机增强转换。它们仅在训练期间有效。\n", "\n", "- `tf.keras.layers.RandomCrop`\n", "- `tf.keras.layers.RandomFlip`\n", "- `tf.keras.layers.RandomTranslation`\n", "- `tf.keras.layers.RandomRotation`\n", "- `tf.keras.layers.RandomZoom`\n", "- `tf.keras.layers.RandomHeight`\n", "- `tf.keras.layers.RandomWidth`\n", "- `tf.keras.layers.RandomContrast`" ] }, { "cell_type": "markdown", "metadata": { "id": "c923e41fb1b4" }, "source": [ "## `adapt()` 方法\n", "\n", "一些预处理层具有可基于训练数据样本计算的内部状态。以下是有状态预处理层的列表:\n", "\n", "- `TextVectorization`:保存字符串词例和整数索引之间的映射。\n", "- `StringLookup` 和 `IntegerLookup`:保存输入值和整数索引之间的映射。\n", "- `Normalization`:保存特征的平均值和标准差。\n", "- `Discretization`:保存值桶边界相关信息。\n", "\n", "至关重要的是,这些层**不可训练**。它们的状态不是在训练期间设定的;必须在**训练之前**设置状态,方法是通过预先计算的常量对其进行初始化,或者基于数据对其进行“调整”。\n", "\n", "您可以通过如下 `adapt()` 方法将预处理层公开给训练数据以设置其状态:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "4cac6bd80812", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "import numpy as np\n", "import tensorflow as tf\n", "from tensorflow.keras import layers\n", "\n", "data = np.array([[0.1, 0.2, 0.3], [0.8, 0.9, 1.0], [1.5, 1.6, 1.7],])\n", "layer = layers.Normalization()\n", "layer.adapt(data)\n", "normalized_data = layer(data)\n", "\n", "print(\"Features mean: %.2f\" % (normalized_data.numpy().mean()))\n", "print(\"Features std: %.2f\" % (normalized_data.numpy().std()))" ] }, { "cell_type": "markdown", "metadata": { "id": "d43b8246b8a3" }, "source": [ "`adapt()` 方法接受 Numpy 数组或 `tf.data.Dataset` 对象。对于 `StringLookup` 和 `TextVectorization`,您还可以传递字符串列表:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "48d95713348a", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "data = [\n", " \"ξεῖν᾽, ἦ τοι μὲν ὄνειροι ἀμήχανοι ἀκριτόμυθοι\",\n", " \"γίγνοντ᾽, οὐδέ τι πάντα τελείεται ἀνθρώποισι.\",\n", " \"δοιαὶ γάρ τε πύλαι ἀμενηνῶν εἰσὶν ὀνείρων:\",\n", " \"αἱ μὲν γὰρ κεράεσσι τετεύχαται, αἱ δ᾽ ἐλέφαντι:\",\n", " \"τῶν οἳ μέν κ᾽ ἔλθωσι διὰ πριστοῦ ἐλέφαντος,\",\n", " \"οἵ ῥ᾽ ἐλεφαίρονται, ἔπε᾽ ἀκράαντα φέροντες:\",\n", " \"οἱ δὲ διὰ ξεστῶν κεράων ἔλθωσι θύραζε,\",\n", " \"οἵ ῥ᾽ ἔτυμα κραίνουσι, βροτῶν ὅτε κέν τις ἴδηται.\",\n", "]\n", "layer = layers.TextVectorization()\n", "layer.adapt(data)\n", "vectorized_text = layer(data)\n", "print(vectorized_text)" ] }, { "cell_type": "markdown", "metadata": { "id": "7619914dfb40" }, "source": [ "此外,自适应层始终公开一个可以通过构造函数参数或权重赋值直接设置状态的选项。如果预期的状态值在构造层时已知,或者是在 `adapt()` 调用之外计算的,则可以在不依赖层的内部计算的情况下对其进行设置。例如,如果 `TextVectorization`、`StringLookup` 或 `IntegerLookup` 层的外部词汇文件已存在,则可以通过在层的构造函数参数中传递词汇文件的路径来将这些文件直接加载到查找表中。\n", "\n", "下面是我们使用预先计算的词汇实例化 `StringLookup` 层的示例:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "9df56efc7f3b", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "vocab = [\"a\", \"b\", \"c\", \"d\"]\n", "data = tf.constant([[\"a\", \"c\", \"d\"], [\"d\", \"z\", \"b\"]])\n", "layer = layers.StringLookup(vocabulary=vocab)\n", "vectorized_data = layer(data)\n", "print(vectorized_data)" ] }, { "cell_type": "markdown", "metadata": { "id": "49cbfe135b00" }, "source": [ "## 在模型之前或模型内部预处理数据\n", "\n", "您可以通过以下两种方式使用预处理层:\n", "\n", "**选项 1**:使它们成为模型的一部分,如下所示:\n", "\n", "```python\n", "inputs = keras.Input(shape=input_shape)\n", "x = preprocessing_layer(inputs)\n", "outputs = rest_of_the_model(x)\n", "model = keras.Model(inputs, outputs)\n", "```\n", "\n", "使用此选项,预处理将在设备上与模型执行的其余部分同步进行,这意味着它将受益于 GPU 加速。如果您在 GPU 上进行训练,那么这是 `Normalization` 层以及所有图像预处理和数据增强层的最佳选择。\n", "\n", "**选项 2**:将它应用到您的 `tf.data.Dataset`,以获得可生成批量预处理数据的数据集,如下所示:\n", "\n", "```python\n", "dataset = dataset.map(lambda x, y: (preprocessing_layer(x), y))\n", "```\n", "\n", "使用此选项,您的预处理将在 CPU 上异步进行,并在进入模型之前进行缓存。此外,如果您对数据集调用 `dataset.prefetch(tf.data.AUTOTUNE)`,则预处理将与训练同时有效进行:\n", "\n", "```python\n", "dataset = dataset.map(lambda x, y: (preprocessing_layer(x), y))\n", "dataset = dataset.prefetch(tf.data.AUTOTUNE)\n", "model.fit(dataset, ...)\n", "```\n", "\n", "这是 `TextVectorization` 和所有结构化数据预处理层的最佳选择。如果您在 CPU 上进行训练并且使用图像预处理层,那么这同样是一个不错的选择。\n", "\n", "**在 TPU 上运行时,应始终将预处理层置于 `tf.data` 流水线中**(`Normalization` 和 `Rescaling` 除外,由于第一层是图像模型,它们在 TPU 上运行良好且被普遍使用)。" ] }, { "cell_type": "markdown", "metadata": { "id": "32f6d2a104b7" }, "source": [ "## 推断时在模型内部进行预处理的好处\n", "\n", "即使您采用选项 2,您稍后也可能需要导出包含预处理层的仅推断端到端模型。这样做的主要好处是**它使您的模型具有可移植性**,并且**有助于降低[训练/应用偏差](https://developers.google.com/machine-learning/guides/rules-of-ml#training-serving_skew)**。\n", "\n", "当所有数据预处理均为模型的一部分时,其他人可以加载和使用您的模型,而无需了解每个特征预计会如何编码和归一化。您的推断模型将能够处理原始图像或原始结构化数据,并且不需要模型的用户了解诸如以下详细信息: 用于文本的词例化方案、用于分类特征的索引方案、图像像素值是归一化为 `[-1, +1]` 还是 `[0, 1]` 等。如果您要将模型导出到其他运行时(例如 TensorFlow.js),那么这尤为强大:您不必在 JavaScript 中重新实现预处理流水线。\n", "\n", "如果您最初将预处理层置于 `tf.data` 流水线内,则可以导出打包有预处理的推断模型。只需实例化一个链接着预处理层和训练模型的新模型即可:\n", "\n", "```python\n", "inputs = keras.Input(shape=input_shape)\n", "x = preprocessing_layer(inputs)\n", "outputs = training_model(x)\n", "inference_model = keras.Model(inputs, outputs)\n", "```" ] }, { "cell_type": "markdown", "metadata": { "id": "b41b381d48d4" }, "source": [ "## 快速秘诀\n", "\n", "### 图像数据增强\n", "\n", "请注意,图像数据增强层仅在训练期间有效(类似于 `Dropout` 层)。" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "a3793692e983", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "from tensorflow import keras\n", "from tensorflow.keras import layers\n", "\n", "# Create a data augmentation stage with horizontal flipping, rotations, zooms\n", "data_augmentation = keras.Sequential(\n", " [\n", " layers.RandomFlip(\"horizontal\"),\n", " layers.RandomRotation(0.1),\n", " layers.RandomZoom(0.1),\n", " ]\n", ")\n", "\n", "# Load some data\n", "(x_train, y_train), _ = keras.datasets.cifar10.load_data()\n", "input_shape = x_train.shape[1:]\n", "classes = 10\n", "\n", "# Create a tf.data pipeline of augmented images (and their labels)\n", "train_dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train))\n", "train_dataset = train_dataset.batch(16).map(lambda x, y: (data_augmentation(x), y))\n", "\n", "\n", "# Create a model and train it on the augmented image data\n", "inputs = keras.Input(shape=input_shape)\n", "x = layers.Rescaling(1.0 / 255)(inputs) # Rescale inputs\n", "outputs = keras.applications.ResNet50( # Add the rest of the model\n", " weights=None, input_shape=input_shape, classes=classes\n", ")(x)\n", "model = keras.Model(inputs, outputs)\n", "model.compile(optimizer=\"rmsprop\", loss=\"sparse_categorical_crossentropy\")\n", "model.fit(train_dataset, steps_per_epoch=5)" ] }, { "cell_type": "markdown", "metadata": { "id": "51d369f0310f" }, "source": [ "您可以在[从零开始进行图像分类](https://keras.io/examples/vision/image_classification_from_scratch/)示例中查看类似设置。" ] }, { "cell_type": "markdown", "metadata": { "id": "a79a1c48b2b7" }, "source": [ "### 归一化数值特征" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "9cc2607a45c8", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "# Load some data\n", "(x_train, y_train), _ = keras.datasets.cifar10.load_data()\n", "x_train = x_train.reshape((len(x_train), -1))\n", "input_shape = x_train.shape[1:]\n", "classes = 10\n", "\n", "# Create a Normalization layer and set its internal state using the training data\n", "normalizer = layers.Normalization()\n", "normalizer.adapt(x_train)\n", "\n", "# Create a model that include the normalization layer\n", "inputs = keras.Input(shape=input_shape)\n", "x = normalizer(inputs)\n", "outputs = layers.Dense(classes, activation=\"softmax\")(x)\n", "model = keras.Model(inputs, outputs)\n", "\n", "# Train the model\n", "model.compile(optimizer=\"adam\", loss=\"sparse_categorical_crossentropy\")\n", "model.fit(x_train, y_train)" ] }, { "cell_type": "markdown", "metadata": { "id": "62685d477010" }, "source": [ "### 通过独热编码进行字符串分类特征编码" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "ae0d2b0405f1", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "# Define some toy data\n", "data = tf.constant([[\"a\"], [\"b\"], [\"c\"], [\"b\"], [\"c\"], [\"a\"]])\n", "\n", "# Use StringLookup to build an index of the feature values and encode output.\n", "lookup = layers.StringLookup(output_mode=\"one_hot\")\n", "lookup.adapt(data)\n", "\n", "# Convert new test data (which includes unknown feature values)\n", "test_data = tf.constant([[\"a\"], [\"b\"], [\"c\"], [\"d\"], [\"e\"], [\"\"]])\n", "encoded_data = lookup(test_data)\n", "print(encoded_data)" ] }, { "cell_type": "markdown", "metadata": { "id": "686aeda532f5" }, "source": [ "请注意,此处的索引 0 为词汇之外的值(`adapt()` 期间未出现的值)保留。\n", "\n", "您可以在[从零开始进行结构化数据分类](https://keras.io/examples/structured_data/structured_data_classification_from_scratch/)示例中查看 `StringLookup` 的实际应用。" ] }, { "cell_type": "markdown", "metadata": { "id": "dc8af3e290df" }, "source": [ "### 通过独热编码进行整数分类特征编码" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "75f3d6af4522", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "# Define some toy data\n", "data = tf.constant([[10], [20], [20], [10], [30], [0]])\n", "\n", "# Use IntegerLookup to build an index of the feature values and encode output.\n", "lookup = layers.IntegerLookup(output_mode=\"one_hot\")\n", "lookup.adapt(data)\n", "\n", "# Convert new test data (which includes unknown feature values)\n", "test_data = tf.constant([[10], [10], [20], [50], [60], [0]])\n", "encoded_data = lookup(test_data)\n", "print(encoded_data)" ] }, { "cell_type": "markdown", "metadata": { "id": "da5a6be487be" }, "source": [ "请注意,索引 0 为缺失值(您应将其指定为值 0)保留,索引 1 为词汇之外的值(`adapt()` 期间未出现的值)保留。您可以使用 `IntegerLookup` 的 `mask_token` 和 `oov_token` 构造函数参数进行配置。\n", "\n", "您可以在[从零开始进行结构化数据分类](https://keras.io/examples/structured_data/structured_data_classification_from_scratch/)示例中看到 `IntegerLookup` 的实际应用。" ] }, { "cell_type": "markdown", "metadata": { "id": "8fbfaa6ab3e2" }, "source": [ "### 对整数分类特征应用哈希技巧\n", "\n", "如果您拥有可以接受许多不同值(约 10e3 或更高次方)的分类特征,其中每个值仅在数据中出现几次,那么对特征值进行索引和独热编码就变得不切实际且低效。相反,应用“哈希技巧”可能是一个好主意:将值散列到固定大小的向量。这使得特征空间的大小易于管理,并且无需显式索引。" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "8f6c1f84c43c", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "# Sample data: 10,000 random integers with values between 0 and 100,000\n", "data = np.random.randint(0, 100000, size=(10000, 1))\n", "\n", "# Use the Hashing layer to hash the values to the range [0, 64]\n", "hasher = layers.Hashing(num_bins=64, salt=1337)\n", "\n", "# Use the CategoryEncoding layer to multi-hot encode the hashed values\n", "encoder = layers.CategoryEncoding(num_tokens=64, output_mode=\"multi_hot\")\n", "encoded_data = encoder(hasher(data))\n", "print(encoded_data.shape)" ] }, { "cell_type": "markdown", "metadata": { "id": "df69b434d327" }, "source": [ "### 将文本编码为词例索引序列\n", "\n", "这是预处理要传递到 `Embedding` 层的文本时应采用的方式。" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "361b561bc88b", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "# Define some text data to adapt the layer\n", "adapt_data = tf.constant(\n", " [\n", " \"The Brain is wider than the Sky\",\n", " \"For put them side by side\",\n", " \"The one the other will contain\",\n", " \"With ease and You beside\",\n", " ]\n", ")\n", "\n", "# Create a TextVectorization layer\n", "text_vectorizer = layers.TextVectorization(output_mode=\"int\")\n", "# Index the vocabulary via `adapt()`\n", "text_vectorizer.adapt(adapt_data)\n", "\n", "# Try out the layer\n", "print(\n", " \"Encoded text:\\n\", text_vectorizer([\"The Brain is deeper than the sea\"]).numpy(),\n", ")\n", "\n", "# Create a simple model\n", "inputs = keras.Input(shape=(None,), dtype=\"int64\")\n", "x = layers.Embedding(input_dim=text_vectorizer.vocabulary_size(), output_dim=16)(inputs)\n", "x = layers.GRU(8)(x)\n", "outputs = layers.Dense(1)(x)\n", "model = keras.Model(inputs, outputs)\n", "\n", "# Create a labeled dataset (which includes unknown tokens)\n", "train_dataset = tf.data.Dataset.from_tensor_slices(\n", " ([\"The Brain is deeper than the sea\", \"for if they are held Blue to Blue\"], [1, 0])\n", ")\n", "\n", "# Preprocess the string inputs, turning them into int sequences\n", "train_dataset = train_dataset.batch(2).map(lambda x, y: (text_vectorizer(x), y))\n", "# Train the model on the int sequences\n", "print(\"\\nTraining model...\")\n", "model.compile(optimizer=\"rmsprop\", loss=\"mse\")\n", "model.fit(train_dataset)\n", "\n", "# For inference, you can export a model that accepts strings as input\n", "inputs = keras.Input(shape=(1,), dtype=\"string\")\n", "x = text_vectorizer(inputs)\n", "outputs = model(x)\n", "end_to_end_model = keras.Model(inputs, outputs)\n", "\n", "# Call the end-to-end model on test data (which includes unknown tokens)\n", "print(\"\\nCalling end-to-end model on test string...\")\n", "test_data = tf.constant([\"The one the other will absorb\"])\n", "test_output = end_to_end_model(test_data)\n", "print(\"Model output:\", test_output)" ] }, { "cell_type": "markdown", "metadata": { "id": "e725dbcae3e4" }, "source": [ "您可以在示例从头开始进行文本分类中查看 `TextVectorization` 层与 Embedding 模式组合的实际使用情况。\n", "\n", "请注意,在训练此类模型时,为了获得最佳性能,您应始终使用 `TextVectorization` 层作为输入流水线的一部分。" ] }, { "cell_type": "markdown", "metadata": { "id": "28c2f2ff61fb" }, "source": [ "### 通过多热编码将文本编码为 ngram 的密集矩阵\n", "\n", "这是预处理要传递到 `Dense` 层的文本时应采用的方式。" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "7bae1c223cd8", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "# Define some text data to adapt the layer\n", "adapt_data = tf.constant(\n", " [\n", " \"The Brain is wider than the Sky\",\n", " \"For put them side by side\",\n", " \"The one the other will contain\",\n", " \"With ease and You beside\",\n", " ]\n", ")\n", "# Instantiate TextVectorization with \"multi_hot\" output_mode\n", "# and ngrams=2 (index all bigrams)\n", "text_vectorizer = layers.TextVectorization(output_mode=\"multi_hot\", ngrams=2)\n", "# Index the bigrams via `adapt()`\n", "text_vectorizer.adapt(adapt_data)\n", "\n", "# Try out the layer\n", "print(\n", " \"Encoded text:\\n\", text_vectorizer([\"The Brain is deeper than the sea\"]).numpy(),\n", ")\n", "\n", "# Create a simple model\n", "inputs = keras.Input(shape=(text_vectorizer.vocabulary_size(),))\n", "outputs = layers.Dense(1)(inputs)\n", "model = keras.Model(inputs, outputs)\n", "\n", "# Create a labeled dataset (which includes unknown tokens)\n", "train_dataset = tf.data.Dataset.from_tensor_slices(\n", " ([\"The Brain is deeper than the sea\", \"for if they are held Blue to Blue\"], [1, 0])\n", ")\n", "\n", "# Preprocess the string inputs, turning them into int sequences\n", "train_dataset = train_dataset.batch(2).map(lambda x, y: (text_vectorizer(x), y))\n", "# Train the model on the int sequences\n", "print(\"\\nTraining model...\")\n", "model.compile(optimizer=\"rmsprop\", loss=\"mse\")\n", "model.fit(train_dataset)\n", "\n", "# For inference, you can export a model that accepts strings as input\n", "inputs = keras.Input(shape=(1,), dtype=\"string\")\n", "x = text_vectorizer(inputs)\n", "outputs = model(x)\n", "end_to_end_model = keras.Model(inputs, outputs)\n", "\n", "# Call the end-to-end model on test data (which includes unknown tokens)\n", "print(\"\\nCalling end-to-end model on test string...\")\n", "test_data = tf.constant([\"The one the other will absorb\"])\n", "test_output = end_to_end_model(test_data)\n", "print(\"Model output:\", test_output)" ] }, { "cell_type": "markdown", "metadata": { "id": "336a4d3426ed" }, "source": [ "### 通过 TF-IDF 加权将文本编码为 ngram 的密集矩阵\n", "\n", "这是在将文本传递到 `Dense` 层之前对其进行预处理的另一种方式。" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "5b6c0fec928e", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "# Define some text data to adapt the layer\n", "adapt_data = tf.constant(\n", " [\n", " \"The Brain is wider than the Sky\",\n", " \"For put them side by side\",\n", " \"The one the other will contain\",\n", " \"With ease and You beside\",\n", " ]\n", ")\n", "# Instantiate TextVectorization with \"tf-idf\" output_mode\n", "# (multi-hot with TF-IDF weighting) and ngrams=2 (index all bigrams)\n", "text_vectorizer = layers.TextVectorization(output_mode=\"tf-idf\", ngrams=2)\n", "# Index the bigrams and learn the TF-IDF weights via `adapt()`\n", "\n", "with tf.device(\"CPU\"):\n", " # A bug that prevents this from running on GPU for now.\n", " text_vectorizer.adapt(adapt_data)\n", "\n", "# Try out the layer\n", "print(\n", " \"Encoded text:\\n\", text_vectorizer([\"The Brain is deeper than the sea\"]).numpy(),\n", ")\n", "\n", "# Create a simple model\n", "inputs = keras.Input(shape=(text_vectorizer.vocabulary_size(),))\n", "outputs = layers.Dense(1)(inputs)\n", "model = keras.Model(inputs, outputs)\n", "\n", "# Create a labeled dataset (which includes unknown tokens)\n", "train_dataset = tf.data.Dataset.from_tensor_slices(\n", " ([\"The Brain is deeper than the sea\", \"for if they are held Blue to Blue\"], [1, 0])\n", ")\n", "\n", "# Preprocess the string inputs, turning them into int sequences\n", "train_dataset = train_dataset.batch(2).map(lambda x, y: (text_vectorizer(x), y))\n", "# Train the model on the int sequences\n", "print(\"\\nTraining model...\")\n", "model.compile(optimizer=\"rmsprop\", loss=\"mse\")\n", "model.fit(train_dataset)\n", "\n", "# For inference, you can export a model that accepts strings as input\n", "inputs = keras.Input(shape=(1,), dtype=\"string\")\n", "x = text_vectorizer(inputs)\n", "outputs = model(x)\n", "end_to_end_model = keras.Model(inputs, outputs)\n", "\n", "# Call the end-to-end model on test data (which includes unknown tokens)\n", "print(\"\\nCalling end-to-end model on test string...\")\n", "test_data = tf.constant([\"The one the other will absorb\"])\n", "test_output = end_to_end_model(test_data)\n", "print(\"Model output:\", test_output)\n" ] }, { "cell_type": "markdown", "metadata": { "id": "143ce01c5558" }, "source": [ "## 重要问题\n", "\n", "### 处理包含非常大的词汇的查找层\n", "\n", "您可能会在 `TextVectorization`、`StringLookup` 层或 `IntegerLookup` 层中处理非常大的词汇。通常,大于 500MB 的词汇就会被视为“非常大”。\n", "\n", "在这种情况下,为了获得最佳性能,您应避免使用 `adapt()`。相反,应提前预先计算您的词汇(可使用 Apache Beam 或 TF Transform 来实现)并将其存储在文件中。然后,在构建时将文件路径作为 `vocabulary` 参数传递,以将词汇加载到层中。\n", "\n", "### 在 TPU pod 上或与 `ParameterServerStrategy` 一起使用查找层。\n", "\n", "有一个未解决的问题,它会导致在 TPU pod 上或通过 `ParameterServerStrategy` 在多台计算机上进行训练时,使用 `TextVectorization`、`StringLookup` 或 `IntegerLookup` 层时出现性能下降。该问题预计将在 TensorFlow 2.7 中得到修正。" ] } ], "metadata": { "colab": { "collapsed_sections": [], "name": "preprocessing_layers.ipynb", "toc_visible": true }, "kernelspec": { "display_name": "Python 3", "name": "python3" } }, "nbformat": 4, "nbformat_minor": 0 }