{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "tghWegsjhpkt" }, "source": [ "##### Copyright 2020 The TensorFlow Authors." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "rSGJWC5biBiG" }, "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": "YuSYVbwEYNHw" }, "source": [ "# TensorFlow Data Validation\n", "***An Example of a Key Component of TensorFlow Extended***" ] }, { "cell_type": "markdown", "metadata": { "id": "rLsMb4vqY244" }, "source": [ "Note: You can run this example right now in a Jupyter-style notebook, no setup required! Just click \"Run in Google Colab\"\n", "\n", "\u003cdiv class=\"devsite-table-wrapper\"\u003e\u003ctable class=\"tfo-notebook-buttons\" align=\"left\"\u003e\n", "\u003ctd\u003e\u003ca target=\"_blank\" href=\"https://www.tensorflow.org/tfx/tutorials/data_validation/tfdv_basic\"\u003e\n", "\u003cimg src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" /\u003eView on TensorFlow.org\u003c/a\u003e\u003c/td\u003e\n", "\u003ctd\u003e\u003ca target=\"_blank\" href=\"https://colab.sandbox.google.com/github/tensorflow/tfx/blob/master/docs/tutorials/data_validation/tfdv_basic.ipynb\"\u003e\n", "\u003cimg src=\"https://www.tensorflow.org/images/colab_logo_32px.png\"\u003eRun in Google Colab\u003c/a\u003e\u003c/td\u003e\n", "\u003ctd\u003e\u003ca target=\"_blank\" href=\"https://github.com/tensorflow/tfx/blob/master/docs/tutorials/data_validation/tfdv_basic.ipynb\"\u003e\n", "\u003cimg width=32px src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\"\u003eView source on GitHub\u003c/a\u003e\u003c/td\u003e\n", "\u003ctd\u003e\u003ca href=\"https://storage.googleapis.com/tensorflow_docs/tfx/docs/tutorials/data_validation/tfdv_basic.ipynb\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/download_logo_32px.png\" /\u003eDownload notebook\u003c/a\u003e\u003c/td\u003e\n", "\u003c/table\u003e\u003c/div\u003e" ] }, { "cell_type": "markdown", "metadata": { "id": "mPt5BHTwy_0F" }, "source": [ "This example colab notebook illustrates how TensorFlow Data Validation (TFDV) can be used to investigate and visualize your dataset. That includes looking at descriptive statistics, inferring a schema, checking for and fixing anomalies, and checking for drift and skew in our dataset. It's important to understand your dataset's characteristics, including how it might change over time in your production pipeline. It's also important to look for anomalies in your data, and to compare your training, evaluation, and serving datasets to make sure that they're consistent.\n", "\n", "We'll use data from the [Taxi Trips dataset](https://data.cityofchicago.org/Transportation/Taxi-Trips/wrvz-psew) released by the City of Chicago.\n", "\n", "Note: This site provides applications using data that has been modified for use from its original source, www.cityofchicago.org, the official website of the City of Chicago. The City of Chicago makes no claims as to the content, accuracy, timeliness, or completeness of any of the data provided at this site. The data provided at this site is subject to change at any time. It is understood that the data provided at this site is being used at one’s own risk.\n", "\n", "[Read more](https://cloud.google.com/bigquery/public-data/chicago-taxi) about the dataset in [Google BigQuery](https://cloud.google.com/bigquery/). Explore the full dataset in the [BigQuery UI](https://bigquery.cloud.google.com/dataset/bigquery-public-data:chicago_taxi_trips).\n", "\n", "Key Point: As a modeler and developer, think about how this data is used and the potential benefits and harm a model's predictions can cause. A model like this could reinforce societal biases and disparities. Is a feature relevant to the problem you want to solve or will it introduce bias? For more information, read about [ML fairness](https://developers.google.com/machine-learning/fairness-overview/)." ] }, { "cell_type": "markdown", "metadata": { "id": "Fnm6Mj3vTGLm" }, "source": [ "The columns in the dataset are:\n", "\u003ctable\u003e\n", "\u003ctr\u003e\u003ctd\u003epickup_community_area\u003c/td\u003e\u003ctd\u003efare\u003c/td\u003e\u003ctd\u003etrip_start_month\u003c/td\u003e\u003c/tr\u003e\n", "\n", "\u003ctr\u003e\u003ctd\u003etrip_start_hour\u003c/td\u003e\u003ctd\u003etrip_start_day\u003c/td\u003e\u003ctd\u003etrip_start_timestamp\u003c/td\u003e\u003c/tr\u003e\n", "\u003ctr\u003e\u003ctd\u003epickup_latitude\u003c/td\u003e\u003ctd\u003epickup_longitude\u003c/td\u003e\u003ctd\u003edropoff_latitude\u003c/td\u003e\u003c/tr\u003e\n", "\u003ctr\u003e\u003ctd\u003edropoff_longitude\u003c/td\u003e\u003ctd\u003etrip_miles\u003c/td\u003e\u003ctd\u003epickup_census_tract\u003c/td\u003e\u003c/tr\u003e\n", "\u003ctr\u003e\u003ctd\u003edropoff_census_tract\u003c/td\u003e\u003ctd\u003epayment_type\u003c/td\u003e\u003ctd\u003ecompany\u003c/td\u003e\u003c/tr\u003e\n", "\u003ctr\u003e\u003ctd\u003etrip_seconds\u003c/td\u003e\u003ctd\u003edropoff_community_area\u003c/td\u003e\u003ctd\u003etips\u003c/td\u003e\u003c/tr\u003e\n", "\u003c/table\u003e" ] }, { "cell_type": "markdown", "metadata": { "id": "nsYC3O-DnYro" }, "source": [ "## Install and import packages\n", "\n", "Install the packages for TensorFlow Data Validation." ] }, { "cell_type": "markdown", "metadata": { "id": "ATF_g5c2g2Ha" }, "source": [ "### Upgrade Pip\n", "\n", "To avoid upgrading Pip in a system when running locally, check to make sure that we're running in Colab. Local systems can of course be upgraded separately." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "b0ISmRq3nY3-" }, "outputs": [], "source": [ "try:\n", " import colab\n", " !pip install --upgrade pip\n", "except:\n", " pass" ] }, { "cell_type": "markdown", "metadata": { "id": "4qBFH1ARcSNk" }, "source": [ "### Install Data Validation packages\n", "\n", "Install the TensorFlow Data Validation packages and dependencies, which takes a few minutes. You may see warnings and errors regarding incompatible dependency versions, which you will resolve in the next section." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "hPJsE5Gkdp8m" }, "outputs": [], "source": [ "print('Installing TensorFlow Data Validation')\n", "!pip install --upgrade 'tensorflow_data_validation[visualization]\u003c2'" ] }, { "cell_type": "markdown", "metadata": { "id": "s_NXX5GaSiZx" }, "source": [ "### Import TensorFlow and reload updated packages\n", "\n", "The prior step updates the default packages in the Gooogle Colab environment, so you must reload the package resources to resolve the new dependencies.\n", "\n", "Note: This step resolves the dependency error from the installation. If you are still experiencing code execution problems after running this code, restart the runtime (Runtime \u003e Restart runtime ...)." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "E2j9VD9HbGWw" }, "outputs": [], "source": [ "import pkg_resources\n", "import importlib\n", "importlib.reload(pkg_resources)" ] }, { "cell_type": "markdown", "metadata": { "id": "IFXK2AdpSpv0" }, "source": [ "Check the versions of TensorFlow and the Data Validation before proceeding. " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "F5rPatTDSCHB" }, "outputs": [], "source": [ "import tensorflow as tf\n", "import tensorflow_data_validation as tfdv\n", "print('TF version:', tf.__version__)\n", "print('TFDV version:', tfdv.version.__version__)" ] }, { "cell_type": "markdown", "metadata": { "id": "5MizoHg1DRlK" }, "source": [ "## Load the dataset\n", "We will download our dataset from Google Cloud Storage." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "x5gfFiTeDa6Y" }, "outputs": [], "source": [ "import os\n", "import tempfile, urllib, zipfile\n", "\n", "# Set up some globals for our file paths\n", "BASE_DIR = tempfile.mkdtemp()\n", "DATA_DIR = os.path.join(BASE_DIR, 'data')\n", "OUTPUT_DIR = os.path.join(BASE_DIR, 'chicago_taxi_output')\n", "TRAIN_DATA = os.path.join(DATA_DIR, 'train', 'data.csv')\n", "EVAL_DATA = os.path.join(DATA_DIR, 'eval', 'data.csv')\n", "SERVING_DATA = os.path.join(DATA_DIR, 'serving', 'data.csv')\n", "\n", "# Download the zip file from GCP and unzip it\n", "zip, headers = urllib.request.urlretrieve('https://storage.googleapis.com/artifacts.tfx-oss-public.appspot.com/datasets/chicago_data.zip')\n", "zipfile.ZipFile(zip).extractall(BASE_DIR)\n", "zipfile.ZipFile(zip).close()\n", "\n", "print(\"Here's what we downloaded:\")\n", "!ls -R {os.path.join(BASE_DIR, 'data')}" ] }, { "cell_type": "markdown", "metadata": { "id": "H0sFmiTbT8-x" }, "source": [ "## Compute and visualize statistics\n", "\n", "First we'll use [`tfdv.generate_statistics_from_csv`](https://www.tensorflow.org/tfx/data_validation/api_docs/python/tfdv/generate_statistics_from_csv) to compute statistics for our training data. (ignore the snappy warnings)\n", "\n", "TFDV can compute descriptive [statistics](https://github.com/tensorflow/metadata/blob/v0.6.0/tensorflow_metadata/proto/v0/statistics.proto) that provide a quick overview of the data in terms of the features that are present and the shapes of their value distributions.\n", "\n", "Internally, TFDV uses [Apache Beam](https://beam.apache.org/)'s data-parallel processing framework to scale the computation of statistics over large datasets. For applications that wish to integrate deeper with TFDV (e.g., attach statistics generation at the end of a data-generation pipeline), the API also exposes a Beam PTransform for statistics generation." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "EE481oMbT-H0" }, "outputs": [], "source": [ "train_stats = tfdv.generate_statistics_from_csv(data_location=TRAIN_DATA)" ] }, { "cell_type": "markdown", "metadata": { "id": "JhXQSxJ2dB_6" }, "source": [ "Now let's use [`tfdv.visualize_statistics`](https://www.tensorflow.org/tfx/data_validation/api_docs/python/tfdv/visualize_statistics), which uses [Facets](https://pair-code.github.io/facets/) to create a succinct visualization of our training data:\n", "\n", "* Notice that numeric features and catagorical features are visualized separately, and that charts are displayed showing the distributions for each feature.\n", "* Notice that features with missing or zero values display a percentage in red as a visual indicator that there may be issues with examples in those features. The percentage is the percentage of examples that have missing or zero values for that feature.\n", "* Notice that there are no examples with values for `pickup_census_tract`. This is an opportunity for dimensionality reduction!\n", "* Try clicking \"expand\" above the charts to change the display\n", "* Try hovering over bars in the charts to display bucket ranges and counts\n", "* Try switching between the log and linear scales, and notice how the log scale reveals much more detail about the `payment_type` categorical feature\n", "* Try selecting \"quantiles\" from the \"Chart to show\" menu, and hover over the markers to show the quantile percentages" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "U3tUKgh7Up3x" }, "outputs": [], "source": [ "# docs-infra: no-execute\n", "tfdv.visualize_statistics(train_stats)" ] }, { "cell_type": "markdown", "metadata": { "id": "Xoc0ijE5LYeQ" }, "source": [ "\u003c!-- \u003cimg class=\"tfo-display-only-on-site\" src=\"images/statistics.png\"/\u003e --\u003e" ] }, { "cell_type": "markdown", "metadata": { "id": "KVR02-y4V0uM" }, "source": [ "## Infer a schema\n", "\n", "Now let's use [`tfdv.infer_schema`](https://www.tensorflow.org/tfx/data_validation/api_docs/python/tfdv/infer_schema) to create a schema for our data. A schema defines constraints for the data that are relevant for ML. Example constraints include the data type of each feature, whether it's numerical or categorical, or the frequency of its presence in the data. For categorical features the schema also defines the domain - the list of acceptable values. Since writing a schema can be a tedious task, especially for datasets with lots of features, TFDV provides a method to generate an initial version of the schema based on the descriptive statistics.\n", "\n", "Getting the schema right is important because the rest of our production pipeline will be relying on the schema that TFDV generates to be correct. The schema also provides documentation for the data, and so is useful when different developers work on the same data. Let's use [`tfdv.display_schema`](https://www.tensorflow.org/tfx/data_validation/api_docs/python/tfdv/display_schema) to display the inferred schema so that we can review it." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "6LLkRJThVr9m" }, "outputs": [], "source": [ "schema = tfdv.infer_schema(statistics=train_stats)\n", "tfdv.display_schema(schema=schema)" ] }, { "cell_type": "markdown", "metadata": { "id": "ZVa3EXE8WEDE" }, "source": [ "## Check evaluation data for errors\n", "\n", "So far we've only been looking at the training data. It's important that our evaluation data is consistent with our training data, including that it uses the same schema. It's also important that the evaluation data includes examples of roughly the same ranges of values for our numerical features as our training data, so that our coverage of the loss surface during evaluation is roughly the same as during training. The same is true for categorical features. Otherwise, we may have training issues that are not identified during evaluation, because we didn't evaluate part of our loss surface.\n", "\n", "* Notice that each feature now includes statistics for both the training and evaluation datasets.\n", "* Notice that the charts now have both the training and evaluation datasets overlaid, making it easy to compare them.\n", "* Notice that the charts now include a percentages view, which can be combined with log or the default linear scales.\n", "* Notice that the mean and median for `trip_miles` are different for the training versus the evaluation datasets. Will that cause problems?\n", "* Wow, the max `tips` is very different for the training versus the evaluation datasets. Will that cause problems?\n", "* Click expand on the Numeric Features chart, and select the log scale. Review the `trip_seconds` feature, and notice the difference in the max. Will evaluation miss parts of the loss surface?" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "j_P0RLYlV6XG" }, "outputs": [], "source": [ "# Compute stats for evaluation data\n", "eval_stats = tfdv.generate_statistics_from_csv(data_location=EVAL_DATA)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "Qn-3fQWJLimn" }, "outputs": [], "source": [ "# docs-infra: no-execute\n", "# Compare evaluation data with training data\n", "tfdv.visualize_statistics(lhs_statistics=eval_stats, rhs_statistics=train_stats,\n", " lhs_name='EVAL_DATASET', rhs_name='TRAIN_DATASET')" ] }, { "cell_type": "markdown", "metadata": { "id": "MS4u82lzLeRh" }, "source": [ "\u003c!-- \u003cimg class=\"tfo-display-only-on-site\" src=\"images/statistics_eval.png\"/\u003e --\u003e" ] }, { "cell_type": "markdown", "metadata": { "id": "ycRRa4leHp84" }, "source": [ "## Check for evaluation anomalies\n", "\n", "Does our evaluation dataset match the schema from our training dataset? This is especially important for categorical features, where we want to identify the range of acceptable values.\n", "\n", "Key Point: What would happen if we tried to evaluate using data with categorical feature values that were not in our training dataset? What about numeric features that are outside the ranges in our training dataset?" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "T7uGVeL2WOam" }, "outputs": [], "source": [ "# Check eval data for errors by validating the eval data stats using the previously inferred schema.\n", "anomalies = tfdv.validate_statistics(statistics=eval_stats, schema=schema)\n", "tfdv.display_anomalies(anomalies)" ] }, { "cell_type": "markdown", "metadata": { "id": "dzxx1gBpJIBa" }, "source": [ "## Fix evaluation anomalies in the schema\n", "\n", "Oops! It looks like we have some new values for `company` in our evaluation data, that we didn't have in our training data. We also have a new value for `payment_type`. These should be considered anomalies, but what we decide to do about them depends on our domain knowledge of the data. If an anomaly truly indicates a data error, then the underlying data should be fixed. Otherwise, we can simply update the schema to include the values in the eval dataset.\n", "\n", "Key Point: How would our evaluation results be affected if we did not fix these problems?\n", "\n", "Unless we change our evaluation dataset we can't fix everything, but we can fix things in the schema that we're comfortable accepting. That includes relaxing our view of what is and what is not an anomaly for particular features, as well as updating our schema to include missing values for categorical features. TFDV has enabled us to discover what we need to fix.\n", "\n", "Let's make those fixes now, and then review one more time." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "legN2nXLWZAc" }, "outputs": [], "source": [ "# Relax the minimum fraction of values that must come from the domain for feature company.\n", "company = tfdv.get_feature(schema, 'company')\n", "company.distribution_constraints.min_domain_mass = 0.9\n", "\n", "# Add new value to the domain of feature payment_type.\n", "payment_type_domain = tfdv.get_domain(schema, 'payment_type')\n", "payment_type_domain.value.append('Prcard')\n", "\n", "# Validate eval stats after updating the schema \n", "updated_anomalies = tfdv.validate_statistics(eval_stats, schema)\n", "tfdv.display_anomalies(updated_anomalies)" ] }, { "cell_type": "markdown", "metadata": { "id": "xNo72YP9LN98" }, "source": [ "Hey, look at that! We verified that the training and evaluation data are now consistent! Thanks TFDV ;)" ] }, { "cell_type": "markdown", "metadata": { "id": "KZ1P4ucHJj5o" }, "source": [ "## Schema Environments" ] }, { "cell_type": "markdown", "metadata": { "id": "qb179jczJppA" }, "source": [ "We also split off a 'serving' dataset for this example, so we should check that too. By default all datasets in a pipeline should use the same schema, but there are often exceptions. For example, in supervised learning we need to include labels in our dataset, but when we serve the model for inference the labels will not be included. In some cases introducing slight schema variations is necessary.\n", "\n", "**Environments** can be used to express such requirements. In particular, features in schema can be associated with a set of environments using `default_environment`, `in_environment` and `not_in_environment`.\n", "\n", "For example, in this dataset the `tips` feature is included as the label for training, but it's missing in the serving data. Without environment specified, it will show up as an anomaly." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "wSZfbnifJuTA" }, "outputs": [], "source": [ "serving_stats = tfdv.generate_statistics_from_csv(SERVING_DATA)\n", "serving_anomalies = tfdv.validate_statistics(serving_stats, schema)\n", "\n", "tfdv.display_anomalies(serving_anomalies)" ] }, { "cell_type": "markdown", "metadata": { "id": "FDYHvZ09LfkT" }, "source": [ "We'll deal with the `tips` feature below. We also have an INT value in our trip seconds, where our schema expected a FLOAT. By making us aware of that difference, TFDV helps uncover inconsistencies in the way the data is generated for training and serving. It's very easy to be unaware of problems like that until model performance suffers, sometimes catastrophically. It may or may not be a significant issue, but in any case this should be cause for further investigation.\n", "\n", "In this case, we can safely convert INT values to FLOATs, so we want to tell TFDV to use our schema to infer the type. Let's do that now." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "OhtYF8aAczpd" }, "outputs": [], "source": [ "options = tfdv.StatsOptions(schema=schema, infer_type_from_schema=True)\n", "serving_stats = tfdv.generate_statistics_from_csv(SERVING_DATA, stats_options=options)\n", "serving_anomalies = tfdv.validate_statistics(serving_stats, schema)\n", "\n", "tfdv.display_anomalies(serving_anomalies)" ] }, { "cell_type": "markdown", "metadata": { "id": "bJjh5rigc5xy" }, "source": [ "Now we just have the `tips` feature (which is our label) showing up as an anomaly ('Column dropped'). Of course we don't expect to have labels in our serving data, so let's tell TFDV to ignore that." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "bnbnw8H6Lp2M" }, "outputs": [], "source": [ "# All features are by default in both TRAINING and SERVING environments.\n", "schema.default_environment.append('TRAINING')\n", "schema.default_environment.append('SERVING')\n", "\n", "# Specify that 'tips' feature is not in SERVING environment.\n", "tfdv.get_feature(schema, 'tips').not_in_environment.append('SERVING')\n", "\n", "serving_anomalies_with_env = tfdv.validate_statistics(\n", " serving_stats, schema, environment='SERVING')\n", "\n", "tfdv.display_anomalies(serving_anomalies_with_env)" ] }, { "cell_type": "markdown", "metadata": { "id": "yteMr3AGMYEp" }, "source": [ "## Check for drift and skew" ] }, { "cell_type": "markdown", "metadata": { "id": "8Ftd5k6AMkPV" }, "source": [ "In addition to checking whether a dataset conforms to the expectations set in the schema, TFDV also provides functionalities to detect drift and skew. TFDV performs this check by comparing the statistics of the different datasets based on the drift/skew comparators specified in the schema.\n", "\n", "### Drift\n", "\n", "Drift detection is supported for categorical features and between consecutive spans of data (i.e., between span N and span N+1), such as between different days of training data. We express drift in terms of [L-infinity distance](https://en.wikipedia.org/wiki/Chebyshev_distance), and you can set the threshold distance so that you receive warnings when the drift is higher than is acceptable. Setting the correct distance is typically an iterative process requiring domain knowledge and experimentation." ] }, { "cell_type": "markdown", "metadata": { "id": "eBFuLpXb6qSp" }, "source": [ "### Skew\n", "\n", "TFDV can detect three different kinds of skew in your data - schema skew, feature skew, and distribution skew.\n", "\n", "#### Schema Skew\n", "\n", "Schema skew occurs when the training and serving data do not conform to the same schema. Both training and serving data are expected to adhere to the same schema. Any expected deviations between the two (such as the label feature being only present in the training data but not in serving) should be specified through environments field in the schema.\n", "\n", "#### Feature Skew\n", "\n", "Feature skew occurs when the feature values that a model trains on are different from the feature values that it sees at serving time. For example, this can happen when:\n", "\n", "* A data source that provides some feature values is modified between training and serving time\n", "* There is different logic for generating features between training and serving. For example, if you apply some transformation only in one of the two code paths.\n", "\n", "#### Distribution Skew\n", "\n", "Distribution skew occurs when the distribution of the training dataset is significantly different from the distribution of the serving dataset. One of the key causes for distribution skew is using different code or different data sources to generate the training dataset. Another reason is a faulty sampling mechanism that chooses a non-representative subsample of the serving data to train on." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "wEUsZm_rOd1Q" }, "outputs": [], "source": [ "# Add skew comparator for 'payment_type' feature.\n", "payment_type = tfdv.get_feature(schema, 'payment_type')\n", "payment_type.skew_comparator.infinity_norm.threshold = 0.01\n", "\n", "# Add drift comparator for 'company' feature.\n", "company=tfdv.get_feature(schema, 'company')\n", "company.drift_comparator.infinity_norm.threshold = 0.001\n", "\n", "skew_anomalies = tfdv.validate_statistics(train_stats, schema,\n", " previous_statistics=eval_stats,\n", " serving_statistics=serving_stats)\n", "\n", "tfdv.display_anomalies(skew_anomalies)" ] }, { "cell_type": "markdown", "metadata": { "id": "1GzbbsPgf0Bg" }, "source": [ "In this example we do see some drift, but it is well below the threshold that we've set." ] }, { "cell_type": "markdown", "metadata": { "id": "wJ5saC9eWvHx" }, "source": [ "## Freeze the schema\n", "\n", "Now that the schema has been reviewed and curated, we will store it in a file to reflect its \"frozen\" state." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "ydkL4DkIWn18" }, "outputs": [], "source": [ "from tensorflow.python.lib.io import file_io\n", "from google.protobuf import text_format\n", "\n", "file_io.recursive_create_dir(OUTPUT_DIR)\n", "schema_file = os.path.join(OUTPUT_DIR, 'schema.pbtxt')\n", "tfdv.write_schema_text(schema, schema_file)\n", "\n", "!cat {schema_file}" ] }, { "cell_type": "markdown", "metadata": { "id": "b8eC59yISdGB" }, "source": [ "## When to use TFDV\n", "\n", "It's easy to think of TFDV as only applying to the start of your training pipeline, as we did here, but in fact it has many uses. Here's a few more:\n", "\n", "* Validating new data for inference to make sure that we haven't suddenly started receiving bad features\n", "* Validating new data for inference to make sure that our model has trained on that part of the decision surface\n", "* Validating our data after we've transformed it and done feature engineering (probably using [TensorFlow Transform](https://www.tensorflow.org/tfx/transform/get_started)) to make sure we haven't done something wrong" ] } ], "metadata": { "colab": { "collapsed_sections": [ "tghWegsjhpkt" ], "name": "tfdv_basic.ipynb", "private_outputs": true, "provenance": [], "toc_visible": true }, "kernelspec": { "display_name": "Python 3", "name": "python3" } }, "nbformat": 4, "nbformat_minor": 0 }