{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "id": "zg02FZzDyEqd" }, "outputs": [], "source": [ "##### Copyright 2019 The TensorFlow Authors.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "2mapZ9afGJ69", "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": "sMYQvJuBi7MS" }, "source": [ "# 使用 Keras 预处理层对结构化数据进行分类" ] }, { "cell_type": "markdown", "metadata": { "id": "8FaL4wnr22oy" }, "source": [ "\n", " \n", " \n", " \n", " \n", "
在 TensorFlow.org 上查看在 Google Colab 中运行在 GitHub 上查看源代码 下载笔记本
" ] }, { "cell_type": "markdown", "metadata": { "id": "Nna1tOKxyEqe" }, "source": [ "本教程演示了如何使用存储在 CSV 文件中的 Kaggle 竞赛中的 PetFinder 数据集的简化版本对结构化数据(例如表格式数据)进行分类。\n", "\n", "您将使用 [Keras](https://tensorflow.google.cn/guide/keras) 定义模型,并将 [Keras 预处理层](https://tensorflow.google.cn/guide/keras/preprocessing_layers)作为将 CSV 文件中的列映射到用于训练模型的特征的桥梁。目标是预测宠物是否会被领养。\n", "\n", "本教程包含以下完整代码:\n", "\n", "- 使用 pandas 将 CSV 文件加载到 DataFrame 中。\n", "- 使用 `tf.data` 构建输入流水线以批处理和打乱行。(请访问 [tf.data:构建 TensorFlow 输入流水线](../../guide/data.ipynb),了解详细信息。)\n", "- 从 CSV 文件中的列映射到用于使用 Keras 预处理层训练模型的特征。\n", "- 使用 Keras 内置方法构建、训练和评估模型。" ] }, { "cell_type": "markdown", "metadata": { "id": "h5xkXCicjFQD" }, "source": [ "注:本教程类似于[使用特征列对结构化数据进行分类](../structured_data/feature_columns.ipynb)。此版本使用 [Keras 预处理层](https://tensorflow.google.cn/guide/keras/preprocessing_layers)而不是 `tf.feature_column` API,因为前者更直观,可以轻松包含在模型中以简化部署。" ] }, { "cell_type": "markdown", "metadata": { "id": "ZHxU1FMNpomc" }, "source": [ "## PetFinder.my mini 数据集\n", "\n", "PetFinder.my mini 的 CSV 数据集文件中有数千行,其中每一行描述一只宠物(狗或猫),每一列描述一个特性(例如年龄、品种、颜色等)。\n", "\n", "在下面的数据集摘要中,请注意主要是数值和分类列。在本教程中,您在数据预处理期间将只处理这两种特征类型,忽略 `Description`(自由文本特征)和 `AdoptionSpeed`(分类特征)。\n", "\n", "列 | 宠物描述 | 特征类型 | 数据类型\n", "--- | --- | --- | ---\n", "`Type` | 动物类型(狗、猫) | 分类 | 字符串\n", "`Age` | 年龄 | 数值 | 整数\n", "`Breed1` | 主要品种 | 分类 | 字符串\n", "`Color1` | 颜色 1 | 分类 | 字符串\n", "`Color2` | 颜色 2 | 分类 | 字符串\n", "`MaturitySize` | 成年个体大小 | 分类 | 字符串\n", "`FurLength` | 毛发长度 | 分类 | 字符串\n", "`Vaccinated` | 宠物已接种疫苗 | 分类 | 字符串\n", "`Sterilized` | 宠物已绝育 | 分类 | 字符串\n", "`Health` | 健康状况 | 分类 | 字符串\n", "`Fee` | 领养费 | 数值 | 整数\n", "`Description` | 资料文字内容 | 文本 | 字符串\n", "`PhotoAmt` | 上传的照片总数 | 数值 | 整数\n", "`AdoptionSpeed` | 分类领养速度 | 分类 | 整数" ] }, { "cell_type": "markdown", "metadata": { "id": "vjFbdBldyEqf" }, "source": [ "## 导入TensorFlow和其他库\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "LklnLlt6yEqf", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "import numpy as np\n", "import pandas as pd\n", "import tensorflow as tf\n", "\n", "from tensorflow.keras import layers" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "TKU7RyoQGVKB", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "tf.__version__" ] }, { "cell_type": "markdown", "metadata": { "id": "UXvBvobayEqi" }, "source": [ "## 加载数据集并将其读入 pandas DataFrame\n", "\n", "pandas 是一个 Python 库,其中包含许多用于加载和处理结构化数据的有用效用函数。使用 `tf.keras.utils.get_file` 下载并提取包含 PetFinder.my mini 数据集的 CSV 文件,并使用 `pandas.read_csv` 将其加载到 DataFrame 中:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "qJ4Ajn-YyEqj", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "dataset_url = 'http://storage.googleapis.com/download.tensorflow.org/data/petfinder-mini.zip'\n", "csv_file = 'datasets/petfinder-mini/petfinder-mini.csv'\n", "\n", "tf.keras.utils.get_file('petfinder_mini.zip', dataset_url,\n", " extract=True, cache_dir='.')\n", "dataframe = pd.read_csv(csv_file)" ] }, { "cell_type": "markdown", "metadata": { "id": "efa6910dfa5f" }, "source": [ "通过检查 DataFrame 的前五行来检查数据集:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "3uiq4hoIGyXI", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "dataframe.head()" ] }, { "cell_type": "markdown", "metadata": { "id": "C3zDbrozyEqq" }, "source": [ "## 创建目标变量\n", "\n", "Kaggle 的 PetFinder.my 领养预测竞赛的最初任务是预测宠物被领养的速度(例如,第一周、第一个月、前三个月等)。\n", "\n", "在本教程中,您将通过将其转换为二元分类问题来简化任务,您只需预测宠物是否被领养。\n", "\n", "修改 `AdoptionSpeed` 列后,`0` 表示宠物未被领养,`1` 表示宠物已被领养。" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "wmMDc46-yEqq", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "# In the original dataset, `'AdoptionSpeed'` of `4` indicates\n", "# a pet was not adopted.\n", "dataframe['target'] = np.where(dataframe['AdoptionSpeed']==4, 0, 1)\n", "\n", "# Drop unused features.\n", "dataframe = dataframe.drop(columns=['AdoptionSpeed', 'Description'])" ] }, { "cell_type": "markdown", "metadata": { "id": "sp0NCbswyEqs" }, "source": [ "## 将 DataFrame 拆分为训练集、验证集和测试集\n", "\n", "数据集位于单个 pandas DataFrame 中。使用 80:10:10 之类的比例将其分别拆分为训练集、验证集和测试集:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "XvSinthO8oMj", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "train, val, test = np.split(dataframe.sample(frac=1), [int(0.8*len(dataframe)), int(0.9*len(dataframe))])" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "U02Q1moWoPwQ", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "print(len(train), 'training examples')\n", "print(len(val), 'validation examples')\n", "print(len(test), 'test examples')" ] }, { "cell_type": "markdown", "metadata": { "id": "C_7uVu-xyEqv" }, "source": [ "## 使用 tf.data 创建输入流水线\n", "\n", "接下来,创建一个效用函数,将每个训练集、验证集和测试集 DataFrame 转换为 `tf.data.Dataset`,然后对数据进行打乱和批处理。\n", "\n", "注:如果您处理的 CSV 文件非常大(大到无法放入内存),则可以使用 `tf.data` API 直接从磁盘读取文件。本教程中没有涉及这方面的内容。" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "7r4j-1lRyEqw", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "def df_to_dataset(dataframe, shuffle=True, batch_size=32):\n", " df = dataframe.copy()\n", " labels = df.pop('target')\n", " df = {key: value[:,tf.newaxis] for key, value in dataframe.items()}\n", " ds = tf.data.Dataset.from_tensor_slices((dict(df), labels))\n", " if shuffle:\n", " ds = ds.shuffle(buffer_size=len(dataframe))\n", " ds = ds.batch(batch_size)\n", " ds = ds.prefetch(batch_size)\n", " return ds" ] }, { "cell_type": "markdown", "metadata": { "id": "PYxIXH579uS9" }, "source": [ "现在,通过在训练数据上调用来使用新创建的函数 (`df_to_dataset`) 检查输入流水线辅助函数返回的数据格式,并使用小批量来保持输出可读:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "tYiNH-QI96Jo", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "batch_size = 5\n", "train_ds = df_to_dataset(train, batch_size=batch_size)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "nFYir6S8HgIJ", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "[(train_features, label_batch)] = train_ds.take(1)\n", "print('Every feature:', list(train_features.keys()))\n", "print('A batch of ages:', train_features['Age'])\n", "print('A batch of targets:', label_batch )" ] }, { "cell_type": "markdown", "metadata": { "id": "geqHWW54Hmte" }, "source": [ "如输出所示,训练集返回了一个列名(来自 DataFrame)字典,列名映射到行中的列值。" ] }, { "cell_type": "markdown", "metadata": { "id": "-v50jBIuj4gb" }, "source": [ "## 应用 Keras 预处理层\n", "\n", "Keras 预处理层允许您构建 Keras 原生输入处理流水线,可在非 Keras 工作流中用作独立预处理代码,直接与 Keras 模型结合,并作为 Keras SavedModel 的一部分导出。\n", "\n", "在本教程中,您将使用以下四个预处理层来演示如何执行预处理、结构化数据编码和特征工程:\n", "\n", "- `tf.keras.layers.Normalization`:对输入特征执行逐特征归一化。\n", "- `tf.keras.layers.CategoryEncoding`:将整数分类特征转换为独热、多热或 tf-idf 密集表示。\n", "- `tf.keras.layers.StringLookup`:将字符串分类值转换为整数索引。\n", "- `tf.keras.layers.IntegerLookup`:将整数分类值转换为整数索引。\n", "\n", "您可以在[使用预处理层指南中](https://tensorflow.google.cn/guide/keras/preprocessing_layers)指南中详细了解可用层。\n", "\n", "- 对于 PetFinder.my mini 数据集的*数值特征*,您将使用 `tf.keras.layers.Normalization` 层来标准化数据分布。\n", "- 对于*分类特征*,例如宠物 `Type`(`Dog` 和 `Cat` 字符串),您将使用 `tf.keras.layers.CategoryEncoding` 将它们转换为多热编码张量。" ] }, { "cell_type": "markdown", "metadata": { "id": "twXBSxnT66o8" }, "source": [ "### 数值列\n", "\n", "对于 PetFinder.my mini 数据集的数值特征,您将使用 `tf.keras.layers.Normalization` 层来标准化数据分布。\n", "\n", "定义一个新的效用函数,该函数返回一个层,后者使用该 Keras 预处理层将逐特征归一化应用于数值特征:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "D6OuEKMMyEq1", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "def get_normalization_layer(name, dataset):\n", " # Create a Normalization layer for the feature.\n", " normalizer = layers.Normalization(axis=None)\n", "\n", " # Prepare a Dataset that only yields the feature.\n", " feature_ds = dataset.map(lambda x, y: x[name])\n", "\n", " # Learn the statistics of the data.\n", " normalizer.adapt(feature_ds)\n", "\n", " return normalizer" ] }, { "cell_type": "markdown", "metadata": { "id": "lL4TRreQCPjV" }, "source": [ "接下来,通过在上传的宠物照片总数特征上调用新函数来测试新函数以归一化 `'PhotoAmt'`:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "MpKgUDyk69bM", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "photo_count_col = train_features['PhotoAmt']\n", "layer = get_normalization_layer('PhotoAmt', train_ds)\n", "layer(photo_count_col)" ] }, { "cell_type": "markdown", "metadata": { "id": "foWY00YBUx9N" }, "source": [ "注:如果您有许多数值特征(数百个或更多),首先将它们连接起来并使用单个 `tf.keras.layers.Normalization` 层会更有效。" ] }, { "cell_type": "markdown", "metadata": { "id": "yVD--2WZ7vmh" }, "source": [ "### 分类列\n", "\n", "数据集中的宠物 `Type` 表示为字符串(`Dog` 和 `Cat`),在馈入模型之前需要进行多热编码。`Age` 特征\n", "\n", "定义另一个新的效用函数,该函数返回一个层,后者将词汇表中的值映射到整数索引,并使用 `tf.keras.layers.StringLookup`、`tf.keras.layers.IntegerLookup` 和 `tf.keras.CategoryEncoding` 预处理层对特征进行多热编码:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "GmgaeRjlDoUO", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "def get_category_encoding_layer(name, dataset, dtype, max_tokens=None):\n", " # Create a layer that turns strings into integer indices.\n", " if dtype == 'string':\n", " index = layers.StringLookup(max_tokens=max_tokens)\n", " # Otherwise, create a layer that turns integer values into integer indices.\n", " else:\n", " index = layers.IntegerLookup(max_tokens=max_tokens)\n", "\n", " # Prepare a `tf.data.Dataset` that only yields the feature.\n", " feature_ds = dataset.map(lambda x, y: x[name])\n", "\n", " # Learn the set of possible values and assign them a fixed integer index.\n", " index.adapt(feature_ds)\n", "\n", " # Encode the integer indices.\n", " encoder = layers.CategoryEncoding(num_tokens=index.vocabulary_size())\n", "\n", " # Apply multi-hot encoding to the indices. The lambda function captures the\n", " # layer, so you can use them, or include them in the Keras Functional model later.\n", " return lambda feature: encoder(index(feature))" ] }, { "cell_type": "markdown", "metadata": { "id": "7b3DwtTeCPjX" }, "source": [ "通过在宠物 `'Type'` 特征上调用来测试 `get_category_encoding_layer` 函数,以将它们转换为多热编码张量:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "X2t2ff9K8PcT", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "test_type_col = train_features['Type']\n", "test_type_layer = get_category_encoding_layer(name='Type',\n", " dataset=train_ds,\n", " dtype='string')\n", "test_type_layer(test_type_col)" ] }, { "cell_type": "markdown", "metadata": { "id": "j6eDongw8knz" }, "source": [ "对宠物 `'Age'` 特征重复该过程:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "7FjBioQ38oNE", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "test_age_col = train_features['Age']\n", "test_age_layer = get_category_encoding_layer(name='Age',\n", " dataset=train_ds,\n", " dtype='int64',\n", " max_tokens=5)\n", "test_age_layer(test_age_col)" ] }, { "cell_type": "markdown", "metadata": { "id": "SiE0glOPkMyh" }, "source": [ "## 预处理所选特征以训练模型\n", "\n", "您已经学习了如何使用多种类型的 Keras 预处理层。接下来,您将:\n", "\n", "- 将前面定义的预处理效用函数应用于 PetFinder.my mini 数据集中的 13 个数值和分类特征。\n", "- 将所有特征输入添加到列表中。\n", "\n", "如开头所述,为了训练模型,您将使用 PetFinder.my mini 数据集的数值(`'PhotoAmt'`、`'Fee'`)和分类(`'Age'`、`'Type'`、`'Color1'`、`'Color2'`、`'Gender'`、`'MaturitySize'`、`'FurLength'`、`'Vaccinated'`、`'Sterilized'`、`'Health'`、`'Breed1'`)特征。\n", "\n", "注:如果您的目标是构建一个准确的模型,请尝试使用自己的更大的数据集,并仔细考虑包含哪些特征最有意义,以及它们应该如何表示。" ] }, { "cell_type": "markdown", "metadata": { "id": "Uj1GoHSZ9R3H" }, "source": [ "之前,您使用了小批次来演示输入流水线。现在让我们创建一个具有更大批次大小 (256) 的新输入流水线:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "Rcv2kQTTo23h", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "batch_size = 256\n", "train_ds = df_to_dataset(train, batch_size=batch_size)\n", "val_ds = df_to_dataset(val, shuffle=False, batch_size=batch_size)\n", "test_ds = df_to_dataset(test, shuffle=False, batch_size=batch_size)" ] }, { "cell_type": "markdown", "metadata": { "id": "5bIGNYN2V7iR" }, "source": [ "归一化数值特征(宠物照片的数量和领养费),并将它们添加到一个名为 `encoded_features` 的输入列表中:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "Q3RBa51VkaAn", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "all_inputs = []\n", "encoded_features = []\n", "\n", "# Numerical features.\n", "for header in ['PhotoAmt', 'Fee']:\n", " numeric_col = tf.keras.Input(shape=(1,), name=header)\n", " normalization_layer = get_normalization_layer(header, train_ds)\n", " encoded_numeric_col = normalization_layer(numeric_col)\n", " all_inputs.append(numeric_col)\n", " encoded_features.append(encoded_numeric_col)" ] }, { "cell_type": "markdown", "metadata": { "id": "qVcUAFd6bvlT" }, "source": [ "将数据集中的整数分类值(宠物年龄)转换为整数索引,执行多热编码,并将生成的特征输入添加到 `encoded_features`:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "1FOMGfZflhoA", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "age_col = tf.keras.Input(shape=(1,), name='Age', dtype='int64')\n", "\n", "encoding_layer = get_category_encoding_layer(name='Age',\n", " dataset=train_ds,\n", " dtype='int64',\n", " max_tokens=5)\n", "encoded_age_col = encoding_layer(age_col)\n", "all_inputs.append(age_col)\n", "encoded_features.append(encoded_age_col)" ] }, { "cell_type": "markdown", "metadata": { "id": "QYzynk6wdqKe" }, "source": [ "对字符串分类值重复相同的步骤:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "K8C8xyiXm-Ie", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "categorical_cols = ['Type', 'Color1', 'Color2', 'Gender', 'MaturitySize',\n", " 'FurLength', 'Vaccinated', 'Sterilized', 'Health', 'Breed1']\n", "\n", "for header in categorical_cols:\n", " categorical_col = tf.keras.Input(shape=(1,), name=header, dtype='string')\n", " encoding_layer = get_category_encoding_layer(name=header,\n", " dataset=train_ds,\n", " dtype='string',\n", " max_tokens=5)\n", " encoded_categorical_col = encoding_layer(categorical_col)\n", " all_inputs.append(categorical_col)\n", " encoded_features.append(encoded_categorical_col)" ] }, { "cell_type": "markdown", "metadata": { "id": "YHSnhz2fyEq3" }, "source": [ "## 创建、编译并训练模型\n" ] }, { "cell_type": "markdown", "metadata": { "id": "IDGyN_wpo0XS" }, "source": [ "下一步是使用 [Keras 函数式 API](https://tensorflow.google.cn/guide/keras/functional) 创建模型。对于模型中的第一层,通过与 `tf.keras.layers.concatenate` 串联将特征输入列表 `encoded_features` 合并到一个向量中。" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "6Yrj-_pr6jyL", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "all_features = tf.keras.layers.concatenate(encoded_features)\n", "x = tf.keras.layers.Dense(32, activation=\"relu\")(all_features)\n", "x = tf.keras.layers.Dropout(0.5)(x)\n", "output = tf.keras.layers.Dense(1)(x)\n", "\n", "model = tf.keras.Model(all_inputs, output)" ] }, { "cell_type": "markdown", "metadata": { "id": "NRLDRcYAefTA" }, "source": [ "使用 Keras `Model.compile` 配置模型:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "GZDb_lJdelSg", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "model.compile(optimizer='adam',\n", " loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),\n", " metrics=[\"accuracy\"])" ] }, { "cell_type": "markdown", "metadata": { "id": "f6mNMfG6yEq5" }, "source": [ "我们来呈现连接图:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "Y7Bkx4c7yEq5", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "# Use `rankdir='LR'` to make the graph horizontal.\n", "tf.keras.utils.plot_model(model, show_shapes=True, rankdir=\"LR\")" ] }, { "cell_type": "markdown", "metadata": { "id": "CED6OStLyEq7" }, "source": [ "接下来,训练和测试模型:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "OQfE3PC6yEq8", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "model.fit(train_ds, epochs=10, validation_data=val_ds)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "T8N2uAdU2Cni", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "loss, accuracy = model.evaluate(test_ds)\n", "print(\"Accuracy\", accuracy)" ] }, { "cell_type": "markdown", "metadata": { "id": "LmZMnTKaCZda" }, "source": [ "## 执行推断\n", "\n", "在您将预处理层包含在模型本身中之后,您开发的模型现在可以直接从 CSV 文件中对行进行分类。\n", "\n", "您现在可以在使用新数据执行推断之前使用 `Model.save` 和 `Model.load_model` [保存和重新加载 Keras 模型](../keras/save_and_load.ipynb):" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "QH9Zy1sBvwOH", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "model.save('my_pet_classifier.keras')\n", "reloaded_model = tf.keras.models.load_model('my_pet_classifier.keras')" ] }, { "cell_type": "markdown", "metadata": { "id": "D973plJrdwQ9" }, "source": [ "要获得新样本的预测,只需调用 Keras `Model.predict` 方法。您只需要做两件事:\n", "\n", "1. 将标量封装成列表,以便具有批次维度(`Model` 只处理批量数据,而非单个样本)。\n", "2. 对每个特征调用 `tf.convert_to_tensor`。" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "rKq4pxtdDa7i", "vscode": { "languageId": "python" } }, "outputs": [], "source": [ "sample = {\n", " 'Type': 'Cat',\n", " 'Age': 3,\n", " 'Breed1': 'Tabby',\n", " 'Gender': 'Male',\n", " 'Color1': 'Black',\n", " 'Color2': 'White',\n", " 'MaturitySize': 'Small',\n", " 'FurLength': 'Short',\n", " 'Vaccinated': 'No',\n", " 'Sterilized': 'No',\n", " 'Health': 'Healthy',\n", " 'Fee': 100,\n", " 'PhotoAmt': 2,\n", "}\n", "\n", "input_dict = {name: tf.convert_to_tensor([value]) for name, value in sample.items()}\n", "predictions = reloaded_model.predict(input_dict)\n", "prob = tf.nn.sigmoid(predictions[0])\n", "\n", "print(\n", " \"This particular pet had a %.1f percent probability \"\n", " \"of getting adopted.\" % (100 * prob)\n", ")" ] }, { "cell_type": "markdown", "metadata": { "id": "XJQQZEiH2FaB" }, "source": [ "注:使用更大、更复杂的数据集进行深度学习通常会获得更好的结果。在处理小型数据集(例如简化的 PetFinder.my 数据集)时,您可以使用决策树随机森林作为强基线。本教程的目标是演示使用结构化数据的机制,以便您在将来使用自己的数据集时清楚从哪里着手。\n" ] }, { "cell_type": "markdown", "metadata": { "id": "k0QAY2Tb2HYG" }, "source": [ "## 后续步骤\n", "\n", "要详细了解如何对结构化数据进行分类,请尝试使用其他数据集。为了提高训练和测试模型的准确率,请仔细考虑模型中要包含哪些特征以及它们应如何表示。\n", "\n", "以下是对数据集的一些建议:\n", "\n", "- [TensorFlow Datasets: MovieLens](https://tensorflow.google.cn/datasets/catalog/movie_lens):来自电影推荐服务的一组电影评级。\n", "- [TensorFlow Datasets: Wine Quality](https://tensorflow.google.cn/datasets/catalog/wine_quality):与葡萄牙“Vinho Verde”葡萄酒的红白变种相关的两个数据集。您还可以在 Kaggle 上找到红葡萄酒品质数据集。\n", "- Kaggle: arXiv Dataset:来自 arXiv 的 170 万篇学术文章的语料库,涵盖物理学、计算机科学、数学、统计学、电气工程学、定量生物学和经济学。\n" ] } ], "metadata": { "colab": { "collapsed_sections": [], "name": "preprocessing_layers.ipynb", "toc_visible": true }, "kernelspec": { "display_name": "Python 3", "name": "python3" } }, "nbformat": 4, "nbformat_minor": 0 }