{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "rNdWfPXCjTjY" }, "source": [ "##### Copyright 2019 The TensorFlow Authors." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "I1dUQ0GejU8N" }, "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": "c05P9g5WjizZ" }, "source": [ "# Classify structured data with feature columns" ] }, { "cell_type": "markdown", "metadata": { "id": "zofH_gCzgplN" }, "source": [ "\n", " \n", " \n", " \n", " \n", "
\n", " \n", " \n", " View on TensorFlow.org\n", " \n", " \n", " \n", " Run in Google Colab\n", " \n", " \n", " \n", " View source on GitHub\n", " \n", " Download notebook\n", "
" ] }, { "cell_type": "markdown", "metadata": { "id": "K1y4OHpGgss7" }, "source": [ "Note: If you are starting a new project to classify structured data, we recommend you use [preprocessing layers](https://www.tensorflow.org/tutorials/structured_data/preprocessing_layers).\n", "\n", "This tutorial demonstrates how to classify structured data (e.g. tabular data in a CSV). We will use [Keras](https://www.tensorflow.org/guide/keras) to define the model, and [feature columns](https://www.tensorflow.org/guide/feature_columns) as a bridge to map from columns in a CSV to features used to train the model. This tutorial contains complete code to:\n", "\n", "* Load a CSV file using [Pandas](https://pandas.pydata.org/).\n", "* Build an input pipeline to batch and shuffle the rows using [tf.data](https://www.tensorflow.org/guide/datasets).\n", "* Map from columns in the CSV to features used to train the model using feature columns.\n", "* Build, train, and evaluate a model using Keras.\n", "\n", "## The Dataset\n", "\n", "We will use a simplified version of the PetFinder [dataset](https://www.kaggle.com/c/petfinder-adoption-prediction). There are several thousand rows in the CSV. Each row describes a pet, and each column describes an attribute. We will use this information to predict the speed at which the pet will be adopted.\n", "\n", "Following is a description of this dataset. Notice there are both numeric and categorical columns. There is a free text column which we will not use in this tutorial.\n", "\n", "Column | Description| Feature Type | Data Type\n", "------------|--------------------|----------------------|-----------------\n", "Type | Type of animal (Dog, Cat) | Categorical | string\n", "Age | Age of the pet | Numerical | integer\n", "Breed1 | Primary breed of the pet | Categorical | string\n", "Color1 | Color 1 of pet | Categorical | string\n", "Color2 | Color 2 of pet | Categorical | string\n", "MaturitySize | Size at maturity | Categorical | string\n", "FurLength | Fur length | Categorical | string\n", "Vaccinated | Pet has been vaccinated | Categorical | string\n", "Sterilized | Pet has been sterilized | Categorical | string\n", "Health | Health Condition | Categorical | string\n", "Fee | Adoption Fee | Numerical | integer\n", "Description | Profile write-up for this pet | Text | string\n", "PhotoAmt | Total uploaded photos for this pet | Numerical | integer\n", "AdoptionSpeed | Speed of adoption | Classification | integer" ] }, { "cell_type": "markdown", "metadata": { "id": "VxyBFc_kKazA" }, "source": [ "## Import TensorFlow and other libraries" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "LuOWVJBz8a6G" }, "outputs": [], "source": [ "!pip install sklearn" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "9dEreb4QKizj" }, "outputs": [], "source": [ "import numpy as np\n", "import pandas as pd\n", "\n", "import tensorflow as tf\n", "\n", "from tensorflow import feature_column\n", "from tensorflow.keras import layers\n", "from sklearn.model_selection import train_test_split" ] }, { "cell_type": "markdown", "metadata": { "id": "KCEhSZcULZ9n" }, "source": [ "## Use Pandas to create a dataframe\n", "\n", "[Pandas](https://pandas.pydata.org/) is a Python library with many helpful utilities for loading and working with structured data. We will use Pandas to download the dataset from a URL, and load it into a dataframe." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "REZ57BXCLdfG" }, "outputs": [], "source": [ "import pathlib\n", "\n", "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": "code", "execution_count": null, "metadata": { "id": "o8QIi0_jT5LM" }, "outputs": [], "source": [ "dataframe.head()" ] }, { "cell_type": "markdown", "metadata": { "id": "awGiBeBWbQC8" }, "source": [ "## Create target variable\n", "\n", "The task in the original dataset is to predict the speed at which a pet will be adopted (e.g., in the first week, the first month, the first three months, and so on). Let's simplify this for our tutorial. Here, we will transform this into a binary classification problem, and simply predict whether the pet was adopted, or not.\n", "\n", "After modifying the label column, 0 will indicate the pet was not adopted, and 1 will indicate it was." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "xcbTpEXWbMDz" }, "outputs": [], "source": [ "# In the original dataset \"4\" indicates the pet was not adopted.\n", "dataframe['target'] = np.where(dataframe['AdoptionSpeed']==4, 0, 1)\n", "\n", "# Drop un-used columns.\n", "dataframe = dataframe.drop(columns=['AdoptionSpeed', 'Description'])" ] }, { "cell_type": "markdown", "metadata": { "id": "u0zhLtQqMPem" }, "source": [ "## Split the dataframe into train, validation, and test\n", "\n", "The dataset we downloaded was a single CSV file. We will split this into train, validation, and test sets." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "YEOpw7LhMYsI" }, "outputs": [], "source": [ "train, test = train_test_split(dataframe, test_size=0.2)\n", "train, val = train_test_split(train, test_size=0.2)\n", "print(len(train), 'train examples')\n", "print(len(val), 'validation examples')\n", "print(len(test), 'test examples')" ] }, { "cell_type": "markdown", "metadata": { "id": "84ef46LXMfvu" }, "source": [ "## Create an input pipeline using tf.data\n", "\n", "Next, we will wrap the dataframes with [tf.data](https://www.tensorflow.org/guide/datasets). This will enable us to use feature columns as a bridge to map from the columns in the Pandas dataframe to features used to train the model. If we were working with a very large CSV file (so large that it does not fit into memory), we would use tf.data to read it from disk directly. That is not covered in this tutorial." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "NkcaMYP-MsRe" }, "outputs": [], "source": [ "# A utility method to create a tf.data dataset from a Pandas Dataframe\n", "def df_to_dataset(dataframe, shuffle=True, batch_size=32):\n", " dataframe = dataframe.copy()\n", " labels = dataframe.pop('target')\n", " ds = tf.data.Dataset.from_tensor_slices((dict(dataframe), labels))\n", " if shuffle:\n", " ds = ds.shuffle(buffer_size=len(dataframe))\n", " ds = ds.batch(batch_size)\n", " return ds" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "CXbbXkJvMy34" }, "outputs": [], "source": [ "batch_size = 5 # A small batch sized is used for demonstration purposes\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": "qRLGSMDzM-dl" }, "source": [ "## Understand the input pipeline\n", "\n", "Now that we have created the input pipeline, let's call it to see the format of the data it returns. We have used a small batch size to keep the output readable." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "CSBo3dUVNFc9" }, "outputs": [], "source": [ "for feature_batch, label_batch in train_ds.take(1):\n", " print('Every feature:', list(feature_batch.keys()))\n", " print('A batch of ages:', feature_batch['Age'])\n", " print('A batch of targets:', label_batch )" ] }, { "cell_type": "markdown", "metadata": { "id": "OT5N6Se-NQsC" }, "source": [ "We can see that the dataset returns a dictionary of column names (from the dataframe) that map to column values from rows in the dataframe." ] }, { "cell_type": "markdown", "metadata": { "id": "ttIvgLRaNoOQ" }, "source": [ "## Demonstrate several types of feature columns\n", "TensorFlow provides many types of feature columns. In this section, we will create several types of feature columns, and demonstrate how they transform a column from the dataframe." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "mxwiHFHuNhmf" }, "outputs": [], "source": [ "# We will use this batch to demonstrate several types of feature columns\n", "example_batch = next(iter(train_ds))[0]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "0wfLB8Q3N3UH" }, "outputs": [], "source": [ "# A utility method to create a feature column\n", "# and to transform a batch of data\n", "def demo(feature_column):\n", " feature_layer = layers.DenseFeatures(feature_column)\n", " print(feature_layer(example_batch).numpy())" ] }, { "cell_type": "markdown", "metadata": { "id": "Q7OEKe82N-Qb" }, "source": [ "### Numeric columns\n", "The output of a feature column becomes the input to the model (using the demo function defined above, we will be able to see exactly how each column from the dataframe is transformed). A [numeric column](https://www.tensorflow.org/api_docs/python/tf/feature_column/numeric_column) is the simplest type of column. It is used to represent real valued features. When using this column, your model will receive the column value from the dataframe unchanged." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "QZTZ0HnHOCxC" }, "outputs": [], "source": [ "photo_count = feature_column.numeric_column('PhotoAmt')\n", "demo(photo_count)" ] }, { "cell_type": "markdown", "metadata": { "id": "7a6ddSyzOKpq" }, "source": [ "In the PetFinder dataset, most columns from the dataframe are categorical." ] }, { "cell_type": "markdown", "metadata": { "id": "IcSxUoYgOlA1" }, "source": [ "### Bucketized columns\n", "Often, you don't want to feed a number directly into the model, but instead split its value into different categories based on numerical ranges. Consider raw data that represents a person's age. Instead of representing age as a numeric column, we could split the age into several buckets using a [bucketized column](https://www.tensorflow.org/api_docs/python/tf/feature_column/bucketized_column). Notice the one-hot values below describe which age range each row matches." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "wJ4Wt3SAOpTQ" }, "outputs": [], "source": [ "age = feature_column.numeric_column('Age')\n", "age_buckets = feature_column.bucketized_column(age, boundaries=[1, 3, 5])\n", "demo(age_buckets)" ] }, { "cell_type": "markdown", "metadata": { "id": "r1tArzewPb-b" }, "source": [ "### Categorical columns\n", "In this dataset, Type is represented as a string (e.g. 'Dog', or 'Cat'). We cannot feed strings directly to a model. Instead, we must first map them to numeric values. The categorical vocabulary columns provide a way to represent strings as a one-hot vector (much like you have seen above with age buckets). The vocabulary can be passed as a list using [categorical_column_with_vocabulary_list](https://www.tensorflow.org/api_docs/python/tf/feature_column/categorical_column_with_vocabulary_list), or loaded from a file using [categorical_column_with_vocabulary_file](https://www.tensorflow.org/api_docs/python/tf/feature_column/categorical_column_with_vocabulary_file)." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "DJ6QnSHkPtOC" }, "outputs": [], "source": [ "animal_type = feature_column.categorical_column_with_vocabulary_list(\n", " 'Type', ['Cat', 'Dog'])\n", "\n", "animal_type_one_hot = feature_column.indicator_column(animal_type)\n", "demo(animal_type_one_hot)" ] }, { "cell_type": "markdown", "metadata": { "id": "LEFPjUr6QmwS" }, "source": [ "### Embedding columns\n", "Suppose instead of having just a few possible strings, we have thousands (or more) values per category. For a number of reasons, as the number of categories grow large, it becomes infeasible to train a neural network using one-hot encodings. We can use an embedding column to overcome this limitation. Instead of representing the data as a one-hot vector of many dimensions, an [embedding column](https://www.tensorflow.org/api_docs/python/tf/feature_column/embedding_column) represents that data as a lower-dimensional, dense vector in which each cell can contain any number, not just 0 or 1. The size of the embedding (8, in the example below) is a parameter that must be tuned.\n", "\n", "Key point: using an embedding column is best when a categorical column has many possible values. We are using one here for demonstration purposes, so you have a complete example you can modify for a different dataset in the future." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "hSlohmr2Q_UU" }, "outputs": [], "source": [ "# Notice the input to the embedding column is the categorical column\n", "# we previously created\n", "breed1 = feature_column.categorical_column_with_vocabulary_list(\n", " 'Breed1', dataframe.Breed1.unique())\n", "breed1_embedding = feature_column.embedding_column(breed1, dimension=8)\n", "demo(breed1_embedding)" ] }, { "cell_type": "markdown", "metadata": { "id": "urFCAvTVRMpB" }, "source": [ "### Hashed feature columns\n", "\n", "Another way to represent a categorical column with a large number of values is to use a [categorical_column_with_hash_bucket](https://www.tensorflow.org/api_docs/python/tf/feature_column/categorical_column_with_hash_bucket). This feature column calculates a hash value of the input, then selects one of the `hash_bucket_size` buckets to encode a string. When using this column, you do not need to provide the vocabulary, and you can choose to make the number of hash_buckets significantly smaller than the number of actual categories to save space.\n", "\n", "Key point: An important downside of this technique is that there may be collisions in which different strings are mapped to the same bucket. In practice, this can work well for some datasets regardless." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "YHU_Aj2nRRDC" }, "outputs": [], "source": [ "breed1_hashed = feature_column.categorical_column_with_hash_bucket(\n", " 'Breed1', hash_bucket_size=10)\n", "demo(feature_column.indicator_column(breed1_hashed))" ] }, { "cell_type": "markdown", "metadata": { "id": "fB94M27DRXtZ" }, "source": [ "### Crossed feature columns\n", "Combining features into a single feature, better known as [feature crosses](https://developers.google.com/machine-learning/glossary/#feature_cross), enables a model to learn separate weights for each combination of features. Here, we will create a new feature that is the cross of Age and Type. Note that `crossed_column` does not build the full table of all possible combinations (which could be very large). Instead, it is backed by a `hashed_column`, so you can choose how large the table is." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "oaPVERd9Rep6" }, "outputs": [], "source": [ "crossed_feature = feature_column.crossed_column([age_buckets, animal_type], hash_bucket_size=10)\n", "demo(feature_column.indicator_column(crossed_feature))" ] }, { "cell_type": "markdown", "metadata": { "id": "ypkI9zx6Rj1q" }, "source": [ "## Choose which columns to use\n", "We have seen how to use several types of feature columns. Now we will use them to train a model. The goal of this tutorial is to show you the complete code (e.g. mechanics) needed to work with feature columns. We have selected a few columns to train our model below arbitrarily.\n", "\n", "Key point: If your aim is to build an accurate model, try a larger dataset of your own, and think carefully about which features are the most meaningful to include, and how they should be represented." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "4PlLY7fORuzA" }, "outputs": [], "source": [ "feature_columns = []\n", "\n", "# numeric cols\n", "for header in ['PhotoAmt', 'Fee', 'Age']:\n", " feature_columns.append(feature_column.numeric_column(header))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "jdF4rXkcDmBl" }, "outputs": [], "source": [ "# bucketized cols\n", "age = feature_column.numeric_column('Age')\n", "age_buckets = feature_column.bucketized_column(age, boundaries=[1, 2, 3, 4, 5])\n", "feature_columns.append(age_buckets)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "RsteO7FGDmNc" }, "outputs": [], "source": [ "# indicator_columns\n", "indicator_column_names = ['Type', 'Color1', 'Color2', 'Gender', 'MaturitySize',\n", " 'FurLength', 'Vaccinated', 'Sterilized', 'Health']\n", "for col_name in indicator_column_names:\n", " categorical_column = feature_column.categorical_column_with_vocabulary_list(\n", " col_name, dataframe[col_name].unique())\n", " indicator_column = feature_column.indicator_column(categorical_column)\n", " feature_columns.append(indicator_column)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "6MhdqQ5uDmYU" }, "outputs": [], "source": [ "# embedding columns\n", "breed1 = feature_column.categorical_column_with_vocabulary_list(\n", " 'Breed1', dataframe.Breed1.unique())\n", "breed1_embedding = feature_column.embedding_column(breed1, dimension=8)\n", "feature_columns.append(breed1_embedding)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "qkzRNfCLDsQf" }, "outputs": [], "source": [ "# crossed columns\n", "age_type_feature = feature_column.crossed_column([age_buckets, animal_type], hash_bucket_size=100)\n", "feature_columns.append(feature_column.indicator_column(age_type_feature))" ] }, { "cell_type": "markdown", "metadata": { "id": "M-nDp8krS_ts" }, "source": [ "### Create a feature layer\n", "Now that we have defined our feature columns, we will use a [DenseFeatures](https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/keras/layers/DenseFeatures) layer to input them to our Keras model." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "6o-El1R2TGQP" }, "outputs": [], "source": [ "feature_layer = tf.keras.layers.DenseFeatures(feature_columns)" ] }, { "cell_type": "markdown", "metadata": { "id": "8cf6vKfgTH0U" }, "source": [ "Earlier, we used a small batch size to demonstrate how feature columns worked. We create a new input pipeline with a larger batch size." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "gcemszoGSse_" }, "outputs": [], "source": [ "batch_size = 32\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": "bBx4Xu0eTXWq" }, "source": [ "## Create, compile, and train the model" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "_YJPPb3xTPeZ" }, "outputs": [], "source": [ "model = tf.keras.Sequential([\n", " feature_layer,\n", " layers.Dense(128, activation='relu'),\n", " layers.Dense(128, activation='relu'),\n", " layers.Dropout(.1),\n", " layers.Dense(1)\n", "])\n", "\n", "model.compile(optimizer='adam',\n", " loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),\n", " metrics=['accuracy'])\n", "\n", "model.fit(train_ds,\n", " validation_data=val_ds,\n", " epochs=10)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "GnFmMOW0Tcaa" }, "outputs": [], "source": [ "loss, accuracy = model.evaluate(test_ds)\n", "print(\"Accuracy\", accuracy)" ] }, { "cell_type": "markdown", "metadata": { "id": "3bdfbq20V6zu" }, "source": [ "Key point: You will typically see best results with deep learning with much larger and more complex datasets. When working with a small dataset like this one, we recommend using a decision tree or random forest as a strong baseline. The goal of this tutorial is not to train an accurate model, but to demonstrate the mechanics of working with structured data, so you have code to use as a starting point when working with your own datasets in the future." ] }, { "cell_type": "markdown", "metadata": { "id": "SotnhVWuHQCw" }, "source": [ "## Next steps\n", "The best way to learn more about classifying structured data is to try it yourself. We suggest finding another dataset to work with, and training a model to classify it using code similar to the above. To improve accuracy, think carefully about which features to include in your model, and how they should be represented." ] } ], "metadata": { "accelerator": "GPU", "colab": { "collapsed_sections": [], "name": "feature_columns.ipynb", "toc_visible": true }, "kernelspec": { "display_name": "Python 3", "name": "python3" } }, "nbformat": 4, "nbformat_minor": 0 }