Missed TensorFlow World? Check out the recap. Learn more

TFX Component Tutorial

A Component-by-Component Introduction to TensorFlow Extended (TFX)

This Colab-based tutorial will interactively walk through each built-in component of TensorFlow Extended (TFX).

It covers every step in an end-to-end machine learning pipeline, from data ingestion to pushing a model to serving.

When you're done, the contents of this notebook can be automatically exported as TFX pipeline source code, which you can orchestrate with Airflow and Beam.

Background

This notebook demonstrates how to use TFX in a Jupyter/Colab environment. Here, we walk through the Chicago Taxi example in an interactive notebook.

Working in an interactive notebook is a useful way to become familiar with the structure of a TFX pipeline. It's also useful when doing development of your own pipelines as a lightweight development environment, but you should be aware that there are differences in the way interactive notebooks are orchestrated, and how they access metadata artifacts.

Orchestration

In a production deployment of TFX, you will use an orchestrator such as Apache Airflow, Kubeflow, or Apache Beam to orchestrate a pre-defined pipeline graph of TFX components. In an interactive notebook, the notebook itself is the orchestrator, running each TFX component as you execute the notebook cells.

Metadata

In a production deployment of TFX, you will access metadata through the ML Metadata (MLMD) API. MLMD stores metadata properties in a database such as MySQL or SQLite, and stores the metadata payloads in a persistent store such as on your filesystem. In an interactive notebook, both properties and payloads are stored in an ephemeral SQLite database in the /tmp directory on the Jupyter notebook or Colab server.

Setup

First, we install and import the necessary packages, set up paths, and download data.

Install TFX

!pip install -q tfx==0.15.0rc0

Import packages

We import necessary packages, including standard TFX component classes.

import os
import pprint
import tempfile
import urllib

import tensorflow.compat.v2 as tf
tf.enable_v2_behavior()
tf.get_logger().propagate = False
pp = pprint.PrettyPrinter()

import tfx
from tfx.components.evaluator.component import Evaluator
from tfx.components.example_gen.csv_example_gen.component import CsvExampleGen
from tfx.components.example_validator.component import ExampleValidator
from tfx.components.model_validator.component import ModelValidator
from tfx.components.pusher.component import Pusher
from tfx.components.schema_gen.component import SchemaGen
from tfx.components.statistics_gen.component import StatisticsGen
from tfx.components.trainer.component import Trainer
from tfx.components.transform.component import Transform
from tfx.orchestration import metadata
from tfx.orchestration import pipeline
from tfx.orchestration.experimental.interactive.interactive_context import InteractiveContext
from tfx.proto import evaluator_pb2
from tfx.proto import pusher_pb2
from tfx.proto import trainer_pb2
from tfx.proto.evaluator_pb2 import SingleSlicingSpec
from tfx.utils.dsl_utils import csv_input
from tensorflow.core.example import example_pb2

%load_ext tfx.orchestration.experimental.interactive.notebook_extensions.skip

Check library versions

print('TensorFlow version: {}'.format(tf.__version__))
print('TFX version: {}'.format(tfx.__version__))
TensorFlow version: 1.15.0
TFX version: 0.15.0rc0

Set up pipeline paths

# This is the root directory for your TFX pip package installation.
_tfx_root = tfx.__path__[0]

# This is the directory containing the TFX Chicago Taxi Pipeline example.
_taxi_root = os.path.join(_tfx_root, 'examples/chicago_taxi_pipeline')

# This is the path where your model will be pushed for serving.
_serving_model_dir = os.path.join(
    tempfile.mkdtemp(), 'serving_model/taxi_simple')

Download example data

We download the example dataset for use in our TFX pipeline.

The dataset we're using is the Taxi Trips dataset released by the City of Chicago. The columns in this dataset are:

pickup_community_areafaretrip_start_month
trip_start_hourtrip_start_daytrip_start_timestamp
pickup_latitudepickup_longitudedropoff_latitude
dropoff_longitudetrip_milespickup_census_tract
dropoff_census_tractpayment_typecompany
trip_secondsdropoff_community_areatips

With this dataset, we will build a model that predicts the tips of a trip.

_data_root = tempfile.mkdtemp(prefix='tfx-data')
DATA_PATH = 'https://raw.githubusercontent.com/tensorflow/tfx/master/tfx/examples/chicago_taxi_pipeline/data/simple/data.csv'
_data_filepath = os.path.join(_data_root, "data.csv")
urllib.request.urlretrieve(DATA_PATH, _data_filepath)
('/tmp/tfx-datamknkjx3f/data.csv', <http.client.HTTPMessage at 0x7f7b3cbaf198>)

Take a quick look at the CSV file.

!head {_data_filepath}
pickup_community_area,fare,trip_start_month,trip_start_hour,trip_start_day,trip_start_timestamp,pickup_latitude,pickup_longitude,dropoff_latitude,dropoff_longitude,trip_miles,pickup_census_tract,dropoff_census_tract,payment_type,company,trip_seconds,dropoff_community_area,tips
60,27.05,10,2,3,1380593700,41.836150155,-87.648787952,,,12.6,,,Cash,Taxi Affiliation Services,1380,,0.0
10,5.85,10,1,2,1382319000,41.985015101,-87.804532006,,,0.0,,,Cash,Taxi Affiliation Services,180,,0.0
14,16.65,5,7,5,1369897200,41.968069,-87.721559063,,,0.0,,,Cash,Dispatch Taxi Affiliation,1080,,0.0
13,16.45,11,12,3,1446554700,41.983636307,-87.723583185,,,6.9,,,Cash,,780,,0.0
16,32.05,12,1,1,1417916700,41.953582125,-87.72345239,,,15.4,,,Cash,,1200,,0.0
30,38.45,10,10,5,1444301100,41.839086906,-87.714003807,,,14.6,,,Cash,,2580,,0.0
11,14.65,1,1,3,1358213400,41.978829526,-87.771166703,,,5.81,,,Cash,,1080,,0.0
33,3.25,5,17,1,1368985500,41.849246754,-87.624135298,,,0.0,,,Cash,Taxi Affiliation Services,0,,0.0
19,47.65,6,15,4,1372258800,41.927260956,-87.765501609,,,0.0,,,Cash,Taxi Affiliation Services,3480,,0.0

Create the InteractiveContext

Last, we create an InteractiveContext, which will allow us to run TFX components interactively in this notebook.

# Here, we create an InteractiveContext using default parameters. This will
# use a temporary directory with an ephemeral ML Metadata database instance.
# To use your own pipeline root or database, the optional properties
# `pipeline_root` and `metadata_connection_config` may be passed to
# InteractiveContext. Calls to InteractiveContext are no-ops outside of the
# notebook.
context = InteractiveContext()

Run TFX components interactively

In the cells that follow, we create TFX components one-by-one, run each of them, and visualize their output artifacts.

ExampleGen

The ExampleGen component is usually at the start of a TFX pipeline. It will:

  1. Split data into training and evaluation sets (by default, 2/3 training + 1/3 eval)
  2. Convert data into the tf.Example format
  3. Copy data into the tfx_root directory for other components to access

ExampleGen takes as input the path to your data source. In our case, this is the _data_root path that contains the downloaded CSV.

example_gen = CsvExampleGen(input=csv_input(_data_root))
context.run(example_gen)

Let's examine the output artifacts of ExampleGen. This component produces two artifacts, training examples and evaluation examples:

%%skip_for_export

for artifact in example_gen.outputs['examples'].get():
  print(artifact.split, artifact.uri)
train /tmp/tfx-interactive-2019-10-31T17_26_51.059127-lj_0ne5j/CsvExampleGen/examples/1/train/
eval /tmp/tfx-interactive-2019-10-31T17_26_51.059127-lj_0ne5j/CsvExampleGen/examples/1/eval/
This cell will be skipped during export to pipeline.

We can also take a look at the first three training examples:

%%skip_for_export

import tensorflow_data_validation as tfdv

# Get the URI of the output artifact representing the training examples, which is a directory
train_uri = example_gen.outputs['examples'].get()[0].uri

# Get the list of files in this directory (all compressed TFRecord files)
tfrecord_filenames = [os.path.join(train_uri, name)
                      for name in os.listdir(train_uri)]

# Create a `TFRecordDataset` to read these files
dataset = tf.data.TFRecordDataset(tfrecord_filenames, compression_type="GZIP")
decoder = tfdv.TFExampleDecoder()

# Iterate over the first 3 records and decode them using a TFExampleDecoder
for tfrecord in dataset.take(3):
  serialized_example = tfrecord.numpy()
  example = decoder.decode(serialized_example)
  pp.pprint(example)
{'company': array([b'Taxi Affiliation Services'], dtype=object),
 'dropoff_census_tract': None,
 'dropoff_community_area': None,
 'dropoff_latitude': None,
 'dropoff_longitude': None,
 'fare': array([5.85], dtype=float32),
 'payment_type': array([b'Cash'], dtype=object),
 'pickup_census_tract': None,
 'pickup_community_area': array([10]),
 'pickup_latitude': array([41.985016], dtype=float32),
 'pickup_longitude': array([-87.804535], dtype=float32),
 'tips': array([0.], dtype=float32),
 'trip_miles': array([0.], dtype=float32),
 'trip_seconds': array([180.], dtype=float32),
 'trip_start_day': array([2]),
 'trip_start_hour': array([1]),
 'trip_start_month': array([10]),
 'trip_start_timestamp': array([1382319000])}
{'company': None,
 'dropoff_census_tract': None,
 'dropoff_community_area': None,
 'dropoff_latitude': None,
 'dropoff_longitude': None,
 'fare': array([38.45], dtype=float32),
 'payment_type': array([b'Cash'], dtype=object),
 'pickup_census_tract': None,
 'pickup_community_area': array([30]),
 'pickup_latitude': array([41.83909], dtype=float32),
 'pickup_longitude': array([-87.714005], dtype=float32),
 'tips': array([0.], dtype=float32),
 'trip_miles': array([14.6], dtype=float32),
 'trip_seconds': array([2580.], dtype=float32),
 'trip_start_day': array([5]),
 'trip_start_hour': array([10]),
 'trip_start_month': array([10]),
 'trip_start_timestamp': array([1444301100])}
{'company': array([b'Taxi Affiliation Services'], dtype=object),
 'dropoff_census_tract': None,
 'dropoff_community_area': None,
 'dropoff_latitude': None,
 'dropoff_longitude': None,
 'fare': array([47.65], dtype=float32),
 'payment_type': array([b'Cash'], dtype=object),
 'pickup_census_tract': None,
 'pickup_community_area': array([19]),
 'pickup_latitude': array([41.92726], dtype=float32),
 'pickup_longitude': array([-87.7655], dtype=float32),
 'tips': array([0.], dtype=float32),
 'trip_miles': array([0.], dtype=float32),
 'trip_seconds': array([3480.], dtype=float32),
 'trip_start_day': array([4]),
 'trip_start_hour': array([15]),
 'trip_start_month': array([6]),
 'trip_start_timestamp': array([1372258800])}
This cell will be skipped during export to pipeline.

Now that ExampleGen has finished ingesting the data, the next step is data analysis.

StatisticsGen

The StatisticsGen component computes statistics over your dataset for data analysis, as well as for use in downstream components. It uses the TensorFlow Data Validation library.

StatisticsGen takes as input the dataset we just ingested using ExampleGen.

statistics_gen = StatisticsGen(
    examples=example_gen.outputs['examples'])
context.run(statistics_gen)

After StatisticsGen finishes running, we can visualize the outputted statistics. Try playing with the different plots!

%%skip_for_export

context.show(statistics_gen.outputs['statistics'])

SchemaGen

The SchemaGen component generates a schema based on your data statistics. (A schema defines the expected bounds, types, and properties of the features in your dataset.) It also uses the TensorFlow Data Validation library.

SchemaGen will take as input the statistics that we generated with StatisticsGen, looking at the training split by default.

schema_gen = SchemaGen(
    statistics=statistics_gen.outputs['statistics'],
    infer_feature_shape=False)
context.run(schema_gen)

After SchemaGen finishes running, we can visualize the generated schema as a table.

%%skip_for_export

context.show(schema_gen.outputs['schema'])
This cell will be skipped during export to pipeline.

Each feature in your dataset shows up as a row in the schema table, alongside its properties. The schema also captures all the values that a categorical feature takes on, denoted as its domain.

To learn more about schemas, see the SchemaGen documentation.

ExampleValidator

The ExampleValidator component detects anomalies in your data, based on the expectations defined by the schema. It also uses the TensorFlow Data Validation library.

ExampleValidator will take as input the statistics from StatisticsGen, and the schema from SchemaGen.

By default, it compares the statistics from the evaluation split to the schema from the training split.

example_validator = ExampleValidator(
    statistics=statistics_gen.outputs['statistics'],
    schema=schema_gen.outputs['schema'])
context.run(example_validator)

After ExampleValidator finishes running, we can visualize the anomalies as a table.

%%skip_for_export

context.show(example_validator.outputs['anomalies'])
This cell will be skipped during export to pipeline.

In the anomalies table, we can see that the company feature takes on new values that were not in the training split. This information can be used to debug model performance, understand how your data evolves over time, and identify data errors.

In our case, this anomaly is innocuous, so we move on to the next step of transforming the data.

Transform

The Transform component performs feature engineering that can be used in training and serving. It uses the TensorFlow Transform library.

Transform will take as input the data from ExampleGen, the schema from SchemaGen, as well as a module that contains user-defined Transform code.

Let's see an example of user-defined Transform code below (for an introduction to the TensorFlow Transform APIs, see the guide). First, we define a few constants for feature engineering:

_taxi_constants_module_file = 'taxi_constants.py'
%%skip_for_export
%%writefile {_taxi_constants_module_file}

# Categorical features are assumed to each have a maximum value in the dataset.
MAX_CATEGORICAL_FEATURE_VALUES = [24, 31, 12]

CATEGORICAL_FEATURE_KEYS = [
    'trip_start_hour', 'trip_start_day', 'trip_start_month',
    'pickup_census_tract', 'dropoff_census_tract', 'pickup_community_area',
    'dropoff_community_area'
]

DENSE_FLOAT_FEATURE_KEYS = ['trip_miles', 'fare', 'trip_seconds']

# Number of buckets used by tf.transform for encoding each feature.
FEATURE_BUCKET_COUNT = 10

BUCKET_FEATURE_KEYS = [
    'pickup_latitude', 'pickup_longitude', 'dropoff_latitude',
    'dropoff_longitude'
]

# Number of vocabulary terms used for encoding VOCAB_FEATURES by tf.transform
VOCAB_SIZE = 1000

# Count of out-of-vocab buckets in which unrecognized VOCAB_FEATURES are hashed.
OOV_SIZE = 10

VOCAB_FEATURE_KEYS = [
    'payment_type',
    'company',
]

# Keys
LABEL_KEY = 'tips'
FARE_KEY = 'fare'

def transformed_name(key):
  return key + '_xf'

Next, we write a preprocessing_fn that takes in raw data as input, and returns transformed features that our model can train on:

_taxi_transform_module_file = 'taxi_transform.py'
%%skip_for_export
%%writefile {_taxi_transform_module_file}

import tensorflow as tf
import tensorflow_transform as tft

import taxi_constants

_DENSE_FLOAT_FEATURE_KEYS = taxi_constants.DENSE_FLOAT_FEATURE_KEYS
_VOCAB_FEATURE_KEYS = taxi_constants.VOCAB_FEATURE_KEYS
_VOCAB_SIZE = taxi_constants.VOCAB_SIZE
_OOV_SIZE = taxi_constants.OOV_SIZE
_FEATURE_BUCKET_COUNT = taxi_constants.FEATURE_BUCKET_COUNT
_BUCKET_FEATURE_KEYS = taxi_constants.BUCKET_FEATURE_KEYS
_CATEGORICAL_FEATURE_KEYS = taxi_constants.CATEGORICAL_FEATURE_KEYS
_FARE_KEY = taxi_constants.FARE_KEY
_LABEL_KEY = taxi_constants.LABEL_KEY
_transformed_name = taxi_constants.transformed_name


def preprocessing_fn(inputs):
  """tf.transform's callback function for preprocessing inputs.
  Args:
    inputs: map from feature keys to raw not-yet-transformed features.
  Returns:
    Map from string feature key to transformed feature operations.
  """
  outputs = {}
  for key in _DENSE_FLOAT_FEATURE_KEYS:
    # Preserve this feature as a dense float, setting nan's to the mean.
    outputs[_transformed_name(key)] = tft.scale_to_z_score(
        _fill_in_missing(inputs[key]))

  for key in _VOCAB_FEATURE_KEYS:
    # Build a vocabulary for this feature.
    outputs[_transformed_name(key)] = tft.compute_and_apply_vocabulary(
        _fill_in_missing(inputs[key]),
        top_k=_VOCAB_SIZE,
        num_oov_buckets=_OOV_SIZE)

  for key in _BUCKET_FEATURE_KEYS:
    outputs[_transformed_name(key)] = tft.bucketize(
        _fill_in_missing(inputs[key]), _FEATURE_BUCKET_COUNT,
        always_return_num_quantiles=False)

  for key in _CATEGORICAL_FEATURE_KEYS:
    outputs[_transformed_name(key)] = _fill_in_missing(inputs[key])

  # Was this passenger a big tipper?
  taxi_fare = _fill_in_missing(inputs[_FARE_KEY])
  tips = _fill_in_missing(inputs[_LABEL_KEY])
  outputs[_transformed_name(_LABEL_KEY)] = tf.where(
      tf.math.is_nan(taxi_fare),
      tf.cast(tf.zeros_like(taxi_fare), tf.int64),
      # Test if the tip was > 20% of the fare.
      tf.cast(
          tf.greater(tips, tf.multiply(taxi_fare, tf.constant(0.2))), tf.int64))

  return outputs


def _fill_in_missing(x):
  """Replace missing values in a SparseTensor.
  Fills in missing values of `x` with '' or 0, and converts to a dense tensor.
  Args:
    x: A `SparseTensor` of rank 2.  Its dense shape should have size at most 1
      in the second dimension.
  Returns:
    A rank 1 tensor where missing values of `x` have been filled in.
  """
  default_value = '' if x.dtype == tf.string else 0
  return tf.squeeze(
      tf.sparse.to_dense(
          tf.SparseTensor(x.indices, x.values, [x.dense_shape[0], 1]),
          default_value),
      axis=1)

Now, we pass in this code to the Transform component and run it to transform your data.

transform = Transform(
    examples=example_gen.outputs['examples'],
    schema=schema_gen.outputs['schema'],
    module_file=os.path.abspath(_taxi_transform_module_file))
context.run(transform)

Let's examine the output artifacts of Transform. This component produces two types of outputs:

  • transform_output is the graph that can perform the preprocessing operations (this graph will be included in the serving and evaluation models).
  • transformed_examples represents the preprocessed training and evaluation data.
transform.outputs
{'transform_output': Channel(
    type_name: TransformPath
    artifacts: [Artifact(type_name: TransformPath, uri: /tmp/tfx-interactive-2019-10-31T17_26_51.059127-lj_0ne5j/Transform/transform_output/5/, split: , id: 8)]
), 'transformed_examples': Channel(
    type_name: ExamplesPath
    artifacts: [Artifact(type_name: ExamplesPath, uri: /tmp/tfx-interactive-2019-10-31T17_26_51.059127-lj_0ne5j/Transform/transformed_examples/5/train/, split: train, id: 9)
    Artifact(type_name: ExamplesPath, uri: /tmp/tfx-interactive-2019-10-31T17_26_51.059127-lj_0ne5j/Transform/transformed_examples/5/eval/, split: eval, id: 10)]
)}

Take a peek at the transform_output artifact. It points to a directory containing three subdirectories.

train_uri = transform.outputs['transform_output'].get()[0].uri
os.listdir(train_uri)
['transformed_metadata', 'transform_fn', 'metadata']

The transform_fn subdirectory contains the actual preprocessing graph. The metadata subdirectory contains the schema of the original data. The transformed_metadata subdirectory contains the schema of the preprocessed data.

We can also take a look at the first three transformed examples:

# Get the URI of the output artifact representing the transformed examples, which is a directory
train_uri = transform.outputs['transformed_examples'].get()[1].uri

# Get the list of files in this directory (all compressed TFRecord files)
tfrecord_filenames = [os.path.join(train_uri, name)
                      for name in os.listdir(train_uri)]

# Create a TFRecordDataset to read these files
dataset = tf.data.TFRecordDataset(tfrecord_filenames, compression_type="GZIP")
decoder = tfdv.TFExampleDecoder()

# Iterate over the first 3 records and decode them using a TFExampleDecoder
for tfrecord in dataset.take(3):
  serialized_example = tfrecord.numpy()
  example = decoder.decode(serialized_example)
  pp.pprint(example)
{'company_xf': array([0]),
 'dropoff_census_tract_xf': array([0.], dtype=float32),
 'dropoff_community_area_xf': array([0.], dtype=float32),
 'dropoff_latitude_xf': array([0]),
 'dropoff_longitude_xf': array([12]),
 'fare_xf': array([1.2655534], dtype=float32),
 'payment_type_xf': array([0]),
 'pickup_census_tract_xf': array([b''], dtype=object),
 'pickup_community_area_xf': array([60]),
 'pickup_latitude_xf': array([1]),
 'pickup_longitude_xf': array([6]),
 'tips_xf': array([0]),
 'trip_miles_xf': array([1.6402295], dtype=float32),
 'trip_seconds_xf': array([0.74973756], dtype=float32),
 'trip_start_day_xf': array([3]),
 'trip_start_hour_xf': array([2]),
 'trip_start_month_xf': array([10])}
{'company_xf': array([1]),
 'dropoff_census_tract_xf': array([0.], dtype=float32),
 'dropoff_community_area_xf': array([0.], dtype=float32),
 'dropoff_latitude_xf': array([0]),
 'dropoff_longitude_xf': array([12]),
 'fare_xf': array([0.4084957], dtype=float32),
 'payment_type_xf': array([0]),
 'pickup_census_tract_xf': array([b''], dtype=object),
 'pickup_community_area_xf': array([14]),
 'pickup_latitude_xf': array([8]),
 'pickup_longitude_xf': array([1]),
 'tips_xf': array([0]),
 'trip_miles_xf': array([-0.45483214], dtype=float32),
 'trip_seconds_xf': array([0.382392], dtype=float32),
 'trip_start_day_xf': array([5]),
 'trip_start_hour_xf': array([7]),
 'trip_start_month_xf': array([5])}
{'company_xf': array([53]),
 'dropoff_census_tract_xf': array([0.], dtype=float32),
 'dropoff_community_area_xf': array([0.], dtype=float32),
 'dropoff_latitude_xf': array([0]),
 'dropoff_longitude_xf': array([12]),
 'fare_xf': array([0.3920139], dtype=float32),
 'payment_type_xf': array([0]),
 'pickup_census_tract_xf': array([b''], dtype=object),
 'pickup_community_area_xf': array([13]),
 'pickup_latitude_xf': array([9]),
 'pickup_longitude_xf': array([0]),
 'tips_xf': array([0]),
 'trip_miles_xf': array([0.6924635], dtype=float32),
 'trip_seconds_xf': array([0.01504643], dtype=float32),
 'trip_start_day_xf': array([3]),
 'trip_start_hour_xf': array([12]),
 'trip_start_month_xf': array([11])}

After the Transform component has transformed your data into features, and the next step is to train a model.

Trainer

The Trainer component will train a model that you define in TensorFlow (either using the Estimator API or the Keras API with model_to_estimator).

Trainer takes as input the schema from SchemaGen, the transformed data and graph from Transform, training parameters, as well as a module that contains user-defined model code.

Let's see an example of user-defined model code below (for an introduction to the TensorFlow Estimator APIs, see the guide):

_taxi_trainer_module_file = 'taxi_trainer.py'
%%skip_for_export
%%writefile {_taxi_trainer_module_file}

import tensorflow as tf
import tensorflow_model_analysis as tfma
import tensorflow_transform as tft
from tensorflow_transform.tf_metadata import schema_utils

import taxi_constants

_DENSE_FLOAT_FEATURE_KEYS = taxi_constants.DENSE_FLOAT_FEATURE_KEYS
_VOCAB_FEATURE_KEYS = taxi_constants.VOCAB_FEATURE_KEYS
_VOCAB_SIZE = taxi_constants.VOCAB_SIZE
_OOV_SIZE = taxi_constants.OOV_SIZE
_FEATURE_BUCKET_COUNT = taxi_constants.FEATURE_BUCKET_COUNT
_BUCKET_FEATURE_KEYS = taxi_constants.BUCKET_FEATURE_KEYS
_CATEGORICAL_FEATURE_KEYS = taxi_constants.CATEGORICAL_FEATURE_KEYS
_MAX_CATEGORICAL_FEATURE_VALUES = taxi_constants.MAX_CATEGORICAL_FEATURE_VALUES
_LABEL_KEY = taxi_constants.LABEL_KEY
_transformed_name = taxi_constants.transformed_name


def _transformed_names(keys):
  return [_transformed_name(key) for key in keys]


# Tf.Transform considers these features as "raw"
def _get_raw_feature_spec(schema):
  return schema_utils.schema_as_feature_spec(schema).feature_spec


def _gzip_reader_fn(filenames):
  """Small utility returning a record reader that can read gzip'ed files."""
  return tf.data.TFRecordDataset(
      filenames,
      compression_type='GZIP')


def _build_estimator(config, hidden_units=None, warm_start_from=None):
  """Build an estimator for predicting the tipping behavior of taxi riders.
  Args:
    config: tf.estimator.RunConfig defining the runtime environment for the
      estimator (including model_dir).
    hidden_units: [int], the layer sizes of the DNN (input layer first)
    warm_start_from: Optional directory to warm start from.
  Returns:
    A dict of the following:
      - estimator: The estimator that will be used for training and eval.
      - train_spec: Spec for training.
      - eval_spec: Spec for eval.
      - eval_input_receiver_fn: Input function for eval.
  """
  real_valued_columns = [
      tf.feature_column.numeric_column(key, shape=())
      for key in _transformed_names(_DENSE_FLOAT_FEATURE_KEYS)
  ]
  categorical_columns = [
      tf.feature_column.categorical_column_with_identity(
          key, num_buckets=_VOCAB_SIZE + _OOV_SIZE, default_value=0)
      for key in _transformed_names(_VOCAB_FEATURE_KEYS)
  ]
  categorical_columns += [
      tf.feature_column.categorical_column_with_identity(
          key, num_buckets=_FEATURE_BUCKET_COUNT, default_value=0)
      for key in _transformed_names(_BUCKET_FEATURE_KEYS)
  ]
  categorical_columns += [
      tf.feature_column.categorical_column_with_identity(  # pylint: disable=g-complex-comprehension
          key,
          num_buckets=num_buckets,
          default_value=0) for key, num_buckets in zip(
              _transformed_names(_CATEGORICAL_FEATURE_KEYS),
              _MAX_CATEGORICAL_FEATURE_VALUES)
  ]
  return tf.estimator.DNNLinearCombinedClassifier(
      config=config,
      linear_feature_columns=categorical_columns,
      dnn_feature_columns=real_valued_columns,
      dnn_hidden_units=hidden_units or [100, 70, 50, 25],
      warm_start_from=warm_start_from)


def _example_serving_receiver_fn(tf_transform_output, schema):
  """Build the serving in inputs.
  Args:
    tf_transform_output: A TFTransformOutput.
    schema: the schema of the input data.
  Returns:
    Tensorflow graph which parses examples, applying tf-transform to them.
  """
  raw_feature_spec = _get_raw_feature_spec(schema)
  raw_feature_spec.pop(_LABEL_KEY)

  raw_input_fn = tf.estimator.export.build_parsing_serving_input_receiver_fn(
      raw_feature_spec, default_batch_size=None)
  serving_input_receiver = raw_input_fn()

  transformed_features = tf_transform_output.transform_raw_features(
      serving_input_receiver.features)

  return tf.estimator.export.ServingInputReceiver(
      transformed_features, serving_input_receiver.receiver_tensors)


def _eval_input_receiver_fn(tf_transform_output, schema):
  """Build everything needed for the tf-model-analysis to run the model.
  Args:
    tf_transform_output: A TFTransformOutput.
    schema: the schema of the input data.
  Returns:
    EvalInputReceiver function, which contains:
      - Tensorflow graph which parses raw untransformed features, applies the
        tf-transform preprocessing operators.
      - Set of raw, untransformed features.
      - Label against which predictions will be compared.
  """
  # Notice that the inputs are raw features, not transformed features here.
  raw_feature_spec = _get_raw_feature_spec(schema)

  serialized_tf_example = tf.placeholder(
      dtype=tf.string, shape=[None], name='input_example_tensor')

  # Add a parse_example operator to the tensorflow graph, which will parse
  # raw, untransformed, tf examples.
  features = tf.parse_example(serialized_tf_example, raw_feature_spec)

  # Now that we have our raw examples, process them through the tf-transform
  # function computed during the preprocessing step.
  transformed_features = tf_transform_output.transform_raw_features(
      features)

  # The key name MUST be 'examples'.
  receiver_tensors = {'examples': serialized_tf_example}

  # NOTE: Model is driven by transformed features (since training works on the
  # materialized output of TFT, but slicing will happen on raw features.
  features.update(transformed_features)

  return tfma.export.EvalInputReceiver(
      features=features,
      receiver_tensors=receiver_tensors,
      labels=transformed_features[_transformed_name(_LABEL_KEY)])


def _input_fn(filenames, tf_transform_output, batch_size=200):
  """Generates features and labels for training or evaluation.
  Args:
    filenames: [str] list of CSV files to read data from.
    tf_transform_output: A TFTransformOutput.
    batch_size: int First dimension size of the Tensors returned by input_fn
  Returns:
    A (features, indices) tuple where features is a dictionary of
      Tensors, and indices is a single Tensor of label indices.
  """
  transformed_feature_spec = (
      tf_transform_output.transformed_feature_spec().copy())

  dataset = tf.data.experimental.make_batched_features_dataset(
      filenames, batch_size, transformed_feature_spec, reader=_gzip_reader_fn)

  transformed_features = dataset.make_one_shot_iterator().get_next()
  # We pop the label because we do not want to use it as a feature while we're
  # training.
  return transformed_features, transformed_features.pop(
      _transformed_name(_LABEL_KEY))


# TFX will call this function
def trainer_fn(hparams, schema):
  """Build the estimator using the high level API.
  Args:
    hparams: Holds hyperparameters used to train the model as name/value pairs.
    schema: Holds the schema of the training examples.
  Returns:
    A dict of the following:
      - estimator: The estimator that will be used for training and eval.
      - train_spec: Spec for training.
      - eval_spec: Spec for eval.
      - eval_input_receiver_fn: Input function for eval.
  """
  # Number of nodes in the first layer of the DNN
  first_dnn_layer_size = 100
  num_dnn_layers = 4
  dnn_decay_factor = 0.7

  train_batch_size = 40
  eval_batch_size = 40

  tf_transform_output = tft.TFTransformOutput(hparams.transform_output)

  train_input_fn = lambda: _input_fn(  # pylint: disable=g-long-lambda
      hparams.train_files,
      tf_transform_output,
      batch_size=train_batch_size)

  eval_input_fn = lambda: _input_fn(  # pylint: disable=g-long-lambda
      hparams.eval_files,
      tf_transform_output,
      batch_size=eval_batch_size)

  train_spec = tf.estimator.TrainSpec(  # pylint: disable=g-long-lambda
      train_input_fn,
      max_steps=hparams.train_steps)

  serving_receiver_fn = lambda: _example_serving_receiver_fn(  # pylint: disable=g-long-lambda
      tf_transform_output, schema)

  exporter = tf.estimator.FinalExporter('chicago-taxi', serving_receiver_fn)
  eval_spec = tf.estimator.EvalSpec(
      eval_input_fn,
      steps=hparams.eval_steps,
      exporters=[exporter],
      name='chicago-taxi-eval')

  run_config = tf.estimator.RunConfig(
      save_checkpoints_steps=999, keep_checkpoint_max=1)

  run_config = run_config.replace(model_dir=hparams.serving_model_dir)

  estimator = _build_estimator(
      # Construct layers sizes with exponetial decay
      hidden_units=[
          max(2, int(first_dnn_layer_size * dnn_decay_factor**i))
          for i in range(num_dnn_layers)
      ],
      config=run_config,
      warm_start_from=hparams.warm_start_from)

  # Create an input receiver for TFMA processing
  receiver_fn = lambda: _eval_input_receiver_fn(  # pylint: disable=g-long-lambda
      tf_transform_output, schema)

  return {
      'estimator': estimator,
      'train_spec': train_spec,
      'eval_spec': eval_spec,
      'eval_input_receiver_fn': receiver_fn
  }

Now, we pass in this code to the Trainer component and run it to train the model.

trainer = Trainer(
    module_file=os.path.abspath(_taxi_trainer_module_file),
    transformed_examples=transform.outputs['transformed_examples'],
    schema=schema_gen.outputs['schema'],
    transform_graph=transform.outputs['transform_graph'],
    train_args=trainer_pb2.TrainArgs(num_steps=10000),
    eval_args=trainer_pb2.EvalArgs(num_steps=5000))
context.run(trainer)

Analyze Training with TensorBoard

Optionally, you can use TensorBoard to analyze the model training that was done in Trainer, and see how well our model trained.

%load_ext tensorboard
%tensorboard --bind_all --logdir {os.path.join(train_uri, 'serving_model_dir')}

Evaluator

The Evaluator component computes model performance metrics over the evaluation set. It uses the TensorFlow Model Analysis library.

Evaluator will take as input the data from ExampleGen, the trained model from Trainer, and slicing configuration.

The slicing configuration allows you to slice your metrics on feature values (e.g. how does your model perform on taxi trips that start at 8am versus 8pm?). See an example of this configuration below:

# An empty slice spec means the overall slice, that is, the whole dataset.
OVERALL_SLICE_SPEC = evaluator_pb2.SingleSlicingSpec()

# Data can be sliced along a feature column
# In this case, data is sliced along feature column trip_start_hour.
FEATURE_COLUMN_SLICE_SPEC = evaluator_pb2.SingleSlicingSpec(
    column_for_slicing=['trip_start_hour'])

ALL_SPECS = [
    OVERALL_SLICE_SPEC,
    FEATURE_COLUMN_SLICE_SPEC
]

Next, we give this configuration to Evaluator and run it.

# Use TFMA to compute a evaluation statistics over features of a model.
evaluator = Evaluator(
    examples=example_gen.outputs['examples'],
    model_exports=trainer.outputs['model'],
    feature_slicing_spec=evaluator_pb2.FeatureSlicingSpec(
        specs=ALL_SPECS
    ))
context.run(evaluator)

After Evaluator finishes running, we can show the default visualization of global metrics on the entire evaluation set.

%%skip_for_export

context.show(evaluator.outputs['output'])

To see the visualization for sliced evaluation metrics, we can directly call the TensorFlow Model Analysis library.

%%skip_for_export

import tensorflow_model_analysis as tfma

# Get the TFMA output result path and load the result.
PATH_TO_RESULT = evaluator.outputs['output'].get()[0].uri
tfma_result = tfma.load_eval_result(PATH_TO_RESULT)

# Show data sliced along feature column trip_start_hour.
tfma.view.render_slicing_metrics(
    tfma_result, slicing_column='trip_start_hour')

This visualization shows the same metrics, but computed at every feature value of trip_start_hour instead of on the entire evaluation set.

TensorFlow Model Analysis supports many other visualizations, such as Fairness Indicators and plotting a time series of model performance. To learn more, see the tutorial.

ModelValidator

The ModelValidator component validates that a newly trained model is better than the previous model. This is useful in a production pipeline setting where you may automatically train and validate a model every day.

In this notebook, we only train one model, so the ModelValidator automatically will label the model as "good".

model_validator = ModelValidator(
    examples=example_gen.outputs['examples'],
    model=trainer.outputs['model'])
context.run(model_validator)

Let's examine the output artifacts of ModelValidator.

%%skip_for_export

model_validator.outputs
{'blessing': Channel(
    type_name: ModelBlessingPath
    artifacts: [Artifact(type_name: ModelBlessingPath, uri: /tmp/tfx-interactive-2019-10-31T17_26_51.059127-lj_0ne5j/ModelValidator/blessing/8/, split: , id: 13)]
)}
This cell will be skipped during export to pipeline.
%%skip_for_export

blessing_uri = model_validator.outputs.blessing.get()[0].uri
!ls -l {blessing_uri}
total 0
-rw-r--r-- 1 root root 0 Oct 31 17:31 BLESSED
This cell will be skipped during export to pipeline.

Pusher

The Pusher component is usually at the end of a TFX pipeline. It checks whether a model has passed validation, and if so, exports the model to _serving_model_dir.

pusher = Pusher(
    model=trainer.outputs['model'],
    model_blessing=model_validator.outputs['blessing'],
    push_destination=pusher_pb2.PushDestination(
        filesystem=pusher_pb2.PushDestination.Filesystem(
            base_directory=_serving_model_dir)))
context.run(pusher)

Let's examine the output artifacts of Pusher.

%%skip_for_export

pusher.outputs
{'model_push': Channel(
    type_name: ModelPushPath
    artifacts: [Artifact(type_name: ModelPushPath, uri: /tmp/tfx-interactive-2019-10-31T17_26_51.059127-lj_0ne5j/Pusher/model_push/9/, split: , id: 14)]
)}
This cell will be skipped during export to pipeline.
%%skip_for_export

push_uri = pusher.outputs.model_push.get()[0].uri
latest_version = max(os.listdir(push_uri))
latest_version_path = os.path.join(push_uri, latest_version)
model = tf.saved_model.load(latest_version_path)

for item in model.signatures.items():
  pp.pprint(item)
('predict',
 <tensorflow.python.eager.wrap_function.WrappedFunction object at 0x7f7b30714908>)
('classification',
 <tensorflow.python.eager.wrap_function.WrappedFunction object at 0x7f7b30162278>)
('regression',
 <tensorflow.python.eager.wrap_function.WrappedFunction object at 0x7f7b301d30b8>)
('serving_default',
 <tensorflow.python.eager.wrap_function.WrappedFunction object at 0x7f7aca6e4080>)
This cell will be skipped during export to pipeline.

We're finished the tour of built-in TFX components!

After you're happy with experimenting with TFX components and code in this notebook, you may want to export it as a pipeline to be orchestrated with Airflow or Beam. See the final section.

Export to pipeline

To export the contents of this notebook as a pipeline to be orchestrated with Airflow or Beam, follow the instructions below.

If you're using Colab, make sure to save this notebook to Google Drive (FileSave a Copy in Drive) for export to work.

1. Mount Google Drive (Colab-only)

If you're using Colab, this notebook needs to mount your Google Drive to be able to access its own .ipynb file.

%%skip_for_export

#@markdown Run this cell and enter the authorization code to mount Google Drive.

import sys

if 'google.colab' in sys.modules:
  # Colab.
  from google.colab import drive

  drive.mount('/content/drive')

2. Select an orchestrator

_runner_type = 'beam' #@param ["beam", "airflow"]
_pipeline_name = 'chicago_taxi_%s' % _runner_type

3. Set up paths for the pipeline

# For Colab notebooks only.
# TODO(USER): Fill out the path to this notebook.
_notebook_filepath = (
    '/content/drive/My Drive/Colab Notebooks/taxi_pipeline_interactive.ipynb')

# For Jupyter notebooks only.
# _notebook_filepath = os.path.join(os.getcwd(),
#                                   'taxi_pipeline_interactive.ipynb')

# TODO(USER): Fill out the paths for the exported pipeline.
_tfx_root = os.path.join(os.environ['HOME'], 'tfx')
_taxi_root = os.path.join(os.environ['HOME'], 'taxi')
_serving_model_dir = os.path.join(_taxi_root, 'serving_model')
_data_root = os.path.join(_taxi_root, 'data', 'simple')
_pipeline_root = os.path.join(_tfx_root, 'pipelines', _pipeline_name)
_metadata_path = os.path.join(_tfx_root, 'metadata', _pipeline_name,
                              'metadata.db')

4. Choose components to include in the pipeline

# TODO(USER): Specify components to be included in the exported pipeline.
components = [
    example_gen, statistics_gen, schema_gen, example_validator, transform,
    trainer, evaluator, model_validator, pusher
]

5. Generate pipeline files

%%skip_for_export

#@markdown Run this cell to generate the pipeline files.

if get_ipython().magics_manager.auto_magic:
  print('Warning: %automagic is ON. Line magics specified without the % prefix '
        'will not be scrubbed during export to pipeline.')

_pipeline_export_filepath = 'export_%s.py' % _pipeline_name
context.export_to_pipeline(notebook_filepath=_notebook_filepath,
                           export_filepath=_pipeline_export_filepath,
                           runner_type=_runner_type)

6. Download pipeline files

%%skip_for_export

#@markdown Run this cell to download the pipeline files as a `.zip`.

if 'google.colab' in sys.modules:
  from google.colab import files
  import zipfile

  zip_export_path = os.path.join(
      tempfile.mkdtemp(), 'export.zip')
  with zipfile.ZipFile(zip_export_path, mode='w') as export_zip:
    export_zip.write(_pipeline_export_filepath)
    export_zip.write(_taxi_constants_module_file)
    export_zip.write(_taxi_transform_module_file)
    export_zip.write(_taxi_trainer_module_file)

  files.download(zip_export_path)

To learn how to run the orchestrated pipeline with Airflow, please refer to the TFX Orchestration Tutorial.