このページは Cloud Translation API によって翻訳されました。
Switch to English

TFXEstimatorコンポーネントチュートリアル

TensorFlow Extended(TFX)のコンポーネントごとの概要

このColabベースのチュートリアルでは、TensorFlow Extended(TFX)の各組み込みコンポーネントについてインタラクティブに説明します。

データの取り込みからモデルのプッシュ、サービス提供まで、エンドツーエンドの機械学習パイプラインのすべてのステップをカバーしています。

完了したら、このノートブックのコンテンツをTFXパイプラインソースコードとして自動的にエクスポートできます。これは、ApacheAirflowおよびApacheBeamとオーケストレーションできます。

バックグラウンド

このノートブックは、Jupyter / Colab環境でTFXを使用する方法を示しています。ここでは、インタラクティブなノートブックでシカゴのタクシーの例を見ていきます。

インタラクティブノートブックでの作業は、TFXパイプラインの構造に慣れるための便利な方法です。軽量の開発環境として独自のパイプラインを開発する場合にも役立ちますが、インタラクティブノートブックのオーケストレーション方法とメタデータアーティファクトへのアクセス方法には違いがあることに注意してください。

オーケストレーション

TFXの本番デプロイメントでは、Apache Airflow、Kubeflow Pipelines、Apache Beamなどのオーケストレーターを使用して、TFXコンポーネントの事前定義されたパイプライングラフをオーケストレーションします。インタラクティブノートブックでは、ノートブック自体がオーケストレーターであり、ノートブックセルを実行するときに各TFXコンポーネントを実行します。

メタデータ

TFXの本番デプロイメントでは、MLメタデータ(MLMD)APIを介してメタデータにアクセスします。 MLMDは、メタデータプロパティをMySQLやSQLiteなどのデータベースに保存し、メタデータペイロードをファイルシステムなどの永続ストアに保存します。インタラクティブノートブックでは、プロパティとペイロードの両方が、JupyterノートブックまたはColabサーバーの/tmpディレクトリにあるエフェメラルSQLiteデータベースに保存されます。

セットアップ

まず、必要なパッケージをインストールしてインポートし、パスを設定して、データをダウンロードします。

アップグレードピップ

ローカルで実行しているときにシステムでPipをアップグレードしないようにするには、Colabで実行していることを確認してください。もちろん、ローカルシステムは個別にアップグレードできます。

try:
  import colab
  !pip install --upgrade pip
except:
  pass

TFXをインストールする

pip install -q -U --use-feature=2020-resolver tfx

ランタイムを再起動しましたか?

上記のセルを初めて実行するときにGoogleColabを使用している場合は、ランタイムを再起動する必要があります([ランタイム]> [ランタイムの再起動...])。これは、Colabがパッケージをロードする方法が原因です。

パッケージをインポートする

標準のTFXコンポーネントクラスを含む必要なパッケージをインポートします。

import os
import pprint
import tempfile
import urllib

import absl
import tensorflow as tf
import tensorflow_model_analysis as tfma
tf.get_logger().propagate = False
pp = pprint.PrettyPrinter()

import tfx
from tfx.components import CsvExampleGen
from tfx.components import Evaluator
from tfx.components import ExampleValidator
from tfx.components import Pusher
from tfx.components import ResolverNode
from tfx.components import SchemaGen
from tfx.components import StatisticsGen
from tfx.components import Trainer
from tfx.components import Transform
from tfx.dsl.experimental import latest_blessed_model_resolver
from tfx.orchestration import metadata
from tfx.orchestration import pipeline
from tfx.orchestration.experimental.interactive.interactive_context import InteractiveContext
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 external_input
from tfx.types import Channel
from tfx.types.standard_artifacts import Model
from tfx.types.standard_artifacts import ModelBlessing

%load_ext tfx.orchestration.experimental.interactive.notebook_extensions.skip
WARNING:absl:RuntimeParameter is only supported on Cloud-based DAG runner currently.

ライブラリのバージョンを確認しましょう。

print('TensorFlow version: {}'.format(tf.__version__))
print('TFX version: {}'.format(tfx.__version__))
TensorFlow version: 2.3.1
TFX version: 0.25.0

パイプラインパスを設定する

# 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')

# Set up logging.
absl.logging.set_verbosity(absl.logging.INFO)

サンプルデータをダウンロードする

TFXパイプラインで使用するサンプルデータセットをダウンロードします。

使用しているデータセットは、シカゴ市がリリースしたタクシー旅行データセットです。このデータセットの列は次のとおりです。

Pickup_community_area運賃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支払いタイプ会社
trip_seconds dropoff_community_areaチップ

このデータセットを使用して、旅行のtipsを予測するモデルを構築します。

_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-dataq0c865u1/data.csv', <http.client.HTTPMessage at 0x7f475c9de780>)

CSVファイルをざっと見てください。

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
,12.45,5,19,6,1400269500,,,,,0.0,,,Credit Card,Chicago Elite Cab Corp. (Chicago Carriag,0,,0.0
,0,3,19,5,1362683700,,,,,0,,,Unknown,Chicago Elite Cab Corp.,300,,0
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

免責事項:このサイトは、元のソースであるシカゴ市の公式Webサイトwww.cityofchicago.orgから使用するために変更されたデータを使用するアプリケーションを提供します。シカゴ市は、このサイトで提供されるデータの内容、正確性、適時性、または完全性について一切の主張を行いません。このサイトで提供されるデータは、いつでも変更される可能性があります。当サイトで提供されているデータは、自己責任で使用されているものと理解しております。

InteractiveContextを作成する

最後に、InteractiveContextを作成します。これにより、このノートブックでTFXコンポーネントをインタラクティブに実行できます。

# 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()
WARNING:absl:InteractiveContext pipeline_root argument not provided: using temporary directory /tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p as root for pipeline outputs.
WARNING:absl:InteractiveContext metadata_connection_config not provided: using SQLite ML Metadata database at /tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/metadata.sqlite.

TFXコンポーネントをインタラクティブに実行する

次のセルでは、TFXコンポーネントを1つずつ作成し、それぞれを実行して、出力アーティファクトを視覚化します。

ExampleGen

ExampleGenコンポーネントは通常、TFXパイプラインの開始時にあります。そうなる:

  1. データをトレーニングセットと評価セットに分割します(デフォルトでは、2/3トレーニング+ 1/3評価)
  2. データをtf.Example形式に変換します
  3. 他のコンポーネントがアクセスできるように、データを_tfx_rootディレクトリにコピーします

ExampleGenは、データソースへのパスを入力として受け取ります。この場合、これはダウンロードされたCSVを含む_data_rootパスです。

example_gen = CsvExampleGen(input=external_input(_data_root))
context.run(example_gen)
WARNING:tensorflow:From <ipython-input-1-2e0190c2dd16>:1: external_input (from tfx.utils.dsl_utils) is deprecated and will be removed in a future version.
Instructions for updating:
external_input is deprecated, directly pass the uri to ExampleGen.

Warning:absl:The "input" argument to the CsvExampleGen component has been deprecated by "input_base". Please update your usage as support for this argument will be removed soon.
INFO:absl:Running driver for CsvExampleGen
INFO:absl:MetadataStore with DB connection initialized
INFO:absl:select span and version = (0, None)
INFO:absl:latest span and version = (0, None)
INFO:absl:Running executor for CsvExampleGen
INFO:absl:Generating examples.
WARNING:apache_beam.runners.interactive.interactive_environment:Dependencies required for Interactive Beam PCollection visualization are not available, please use: `pip install apache-beam[interactive]` to install necessary dependencies to enable all data visualization features.

INFO:absl:Processing input csv data /tmp/tfx-dataq0c865u1/* to TFExample.
WARNING:apache_beam.io.tfrecordio:Couldn't find python-snappy so the implementation of _TFRecordUtil._masked_crc32c is not as fast as it could be.
INFO:absl:Examples generated.
INFO:absl:Running publisher for CsvExampleGen
INFO:absl:MetadataStore with DB connection initialized

ExampleGenの出力アーティファクトを調べてみましょう。このコンポーネントは、トレーニング例と評価例の2つのアーティファクトを生成します。

artifact = example_gen.outputs['examples'].get()[0]
print(artifact.split_names, artifact.uri)
["train", "eval"] /tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/CsvExampleGen/examples/1

また、最初の3つのトレーニング例を確認することもできます。

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

# 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")

# Iterate over the first 3 records and decode them.
for tfrecord in dataset.take(3):
  serialized_example = tfrecord.numpy()
  example = tf.train.Example()
  example.ParseFromString(serialized_example)
  pp.pprint(example)
features {
  feature {
    key: "company"
    value {
      bytes_list {
        value: "Chicago Elite Cab Corp. (Chicago Carriag"
      }
    }
  }
  feature {
    key: "dropoff_census_tract"
    value {
      int64_list {
      }
    }
  }
  feature {
    key: "dropoff_community_area"
    value {
      int64_list {
      }
    }
  }
  feature {
    key: "dropoff_latitude"
    value {
      float_list {
      }
    }
  }
  feature {
    key: "dropoff_longitude"
    value {
      float_list {
      }
    }
  }
  feature {
    key: "fare"
    value {
      float_list {
        value: 12.449999809265137
      }
    }
  }
  feature {
    key: "payment_type"
    value {
      bytes_list {
        value: "Credit Card"
      }
    }
  }
  feature {
    key: "pickup_census_tract"
    value {
      int64_list {
      }
    }
  }
  feature {
    key: "pickup_community_area"
    value {
      int64_list {
      }
    }
  }
  feature {
    key: "pickup_latitude"
    value {
      float_list {
      }
    }
  }
  feature {
    key: "pickup_longitude"
    value {
      float_list {
      }
    }
  }
  feature {
    key: "tips"
    value {
      float_list {
        value: 0.0
      }
    }
  }
  feature {
    key: "trip_miles"
    value {
      float_list {
        value: 0.0
      }
    }
  }
  feature {
    key: "trip_seconds"
    value {
      int64_list {
        value: 0
      }
    }
  }
  feature {
    key: "trip_start_day"
    value {
      int64_list {
        value: 6
      }
    }
  }
  feature {
    key: "trip_start_hour"
    value {
      int64_list {
        value: 19
      }
    }
  }
  feature {
    key: "trip_start_month"
    value {
      int64_list {
        value: 5
      }
    }
  }
  feature {
    key: "trip_start_timestamp"
    value {
      int64_list {
        value: 1400269500
      }
    }
  }
}

features {
  feature {
    key: "company"
    value {
      bytes_list {
        value: "Taxi Affiliation Services"
      }
    }
  }
  feature {
    key: "dropoff_census_tract"
    value {
      int64_list {
      }
    }
  }
  feature {
    key: "dropoff_community_area"
    value {
      int64_list {
      }
    }
  }
  feature {
    key: "dropoff_latitude"
    value {
      float_list {
      }
    }
  }
  feature {
    key: "dropoff_longitude"
    value {
      float_list {
      }
    }
  }
  feature {
    key: "fare"
    value {
      float_list {
        value: 27.049999237060547
      }
    }
  }
  feature {
    key: "payment_type"
    value {
      bytes_list {
        value: "Cash"
      }
    }
  }
  feature {
    key: "pickup_census_tract"
    value {
      int64_list {
      }
    }
  }
  feature {
    key: "pickup_community_area"
    value {
      int64_list {
        value: 60
      }
    }
  }
  feature {
    key: "pickup_latitude"
    value {
      float_list {
        value: 41.836151123046875
      }
    }
  }
  feature {
    key: "pickup_longitude"
    value {
      float_list {
        value: -87.64878845214844
      }
    }
  }
  feature {
    key: "tips"
    value {
      float_list {
        value: 0.0
      }
    }
  }
  feature {
    key: "trip_miles"
    value {
      float_list {
        value: 12.600000381469727
      }
    }
  }
  feature {
    key: "trip_seconds"
    value {
      int64_list {
        value: 1380
      }
    }
  }
  feature {
    key: "trip_start_day"
    value {
      int64_list {
        value: 3
      }
    }
  }
  feature {
    key: "trip_start_hour"
    value {
      int64_list {
        value: 2
      }
    }
  }
  feature {
    key: "trip_start_month"
    value {
      int64_list {
        value: 10
      }
    }
  }
  feature {
    key: "trip_start_timestamp"
    value {
      int64_list {
        value: 1380593700
      }
    }
  }
}

features {
  feature {
    key: "company"
    value {
      bytes_list {
      }
    }
  }
  feature {
    key: "dropoff_census_tract"
    value {
      int64_list {
      }
    }
  }
  feature {
    key: "dropoff_community_area"
    value {
      int64_list {
      }
    }
  }
  feature {
    key: "dropoff_latitude"
    value {
      float_list {
      }
    }
  }
  feature {
    key: "dropoff_longitude"
    value {
      float_list {
      }
    }
  }
  feature {
    key: "fare"
    value {
      float_list {
        value: 16.450000762939453
      }
    }
  }
  feature {
    key: "payment_type"
    value {
      bytes_list {
        value: "Cash"
      }
    }
  }
  feature {
    key: "pickup_census_tract"
    value {
      int64_list {
      }
    }
  }
  feature {
    key: "pickup_community_area"
    value {
      int64_list {
        value: 13
      }
    }
  }
  feature {
    key: "pickup_latitude"
    value {
      float_list {
        value: 41.98363494873047
      }
    }
  }
  feature {
    key: "pickup_longitude"
    value {
      float_list {
        value: -87.72357940673828
      }
    }
  }
  feature {
    key: "tips"
    value {
      float_list {
        value: 0.0
      }
    }
  }
  feature {
    key: "trip_miles"
    value {
      float_list {
        value: 6.900000095367432
      }
    }
  }
  feature {
    key: "trip_seconds"
    value {
      int64_list {
        value: 780
      }
    }
  }
  feature {
    key: "trip_start_day"
    value {
      int64_list {
        value: 3
      }
    }
  }
  feature {
    key: "trip_start_hour"
    value {
      int64_list {
        value: 12
      }
    }
  }
  feature {
    key: "trip_start_month"
    value {
      int64_list {
        value: 11
      }
    }
  }
  feature {
    key: "trip_start_timestamp"
    value {
      int64_list {
        value: 1446554700
      }
    }
  }
}


ExampleGenがデータのExampleGenを完了したので、次のステップはデータ分析です。

StatisticsGen

StatisticsGenコンポーネントは、データ分析のため、およびダウンストリームコンポーネントで使用するために、データセットの統計を計算します。 TensorFlowデータ検証ライブラリを使用します。

StatisticsGenは、 ExampleGenを使用してExampleGenデータセットを入力としてExampleGenます。

statistics_gen = StatisticsGen(
    examples=example_gen.outputs['examples'])
context.run(statistics_gen)
INFO:absl:Excluding no splits because exclude_splits is not set.
INFO:absl:Running driver for StatisticsGen
INFO:absl:MetadataStore with DB connection initialized
INFO:absl:Running executor for StatisticsGen
INFO:absl:Generating statistics for split train.
INFO:absl:Statistics for split train written to /tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/StatisticsGen/statistics/2/train.
INFO:absl:Generating statistics for split eval.
INFO:absl:Statistics for split eval written to /tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/StatisticsGen/statistics/2/eval.
INFO:absl:Running publisher for StatisticsGen
INFO:absl:MetadataStore with DB connection initialized

StatisticsGen実行が終了したら、出力された統計を視覚化できます。別のプロットで遊んでみてください!

context.show(statistics_gen.outputs['statistics'])
WARNING:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow_data_validation/utils/stats_util.py:247: tf_record_iterator (from tensorflow.python.lib.io.tf_record) is deprecated and will be removed in a future version.
Instructions for updating:
Use eager execution and: 
`tf.data.TFRecordDataset(path)`

SchemaGen

SchemaGenコンポーネントは、データ統計に基づいてスキーマを生成します。 (スキーマは、データセット内の機能の予想される境界、タイプ、およびプロパティを定義します。)また、 TensorFlowデータ検証ライブラリを使用します。

SchemaGenは、 StatisticsGenで生成したStatisticsGenを入力として受け取り、デフォルトで分割されたトレーニングを確認します。

schema_gen = SchemaGen(
    statistics=statistics_gen.outputs['statistics'],
    infer_feature_shape=False)
context.run(schema_gen)
INFO:absl:Excluding no splits because exclude_splits is not set.
INFO:absl:Running driver for SchemaGen
INFO:absl:MetadataStore with DB connection initialized
INFO:absl:Running executor for SchemaGen
INFO:absl:Processing schema from statistics for split train.
INFO:absl:Processing schema from statistics for split eval.
INFO:absl:Schema written to /tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/SchemaGen/schema/3/schema.pbtxt.
INFO:absl:Running publisher for SchemaGen
INFO:absl:MetadataStore with DB connection initialized

SchemaGen実行が終了しSchemaGen 、生成されたスキーマをテーブルとして視覚化できます。

context.show(schema_gen.outputs['schema'])
/tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow_data_validation/utils/display_util.py:151: FutureWarning: Passing a negative integer is deprecated in version 1.0 and will not be supported in future version. Instead, use None to not limit the column width.
  pd.set_option('max_colwidth', -1)

データセット内の各機能は、そのプロパティとともにスキーマテーブルの行として表示されます。スキーマは、ドメインとして示される、カテゴリ機能がとるすべての値もキャプチャします。

スキーマの詳細については、SchemaGenのドキュメントを参照してください。

ExampleValidator

ExampleValidatorコンポーネントは、スキーマで定義された期待値に基づいて、データの異常を検出します。また、 TensorFlowデータ検証ライブラリを使用します。

ExampleValidatorは、 StatisticsGenからのStatisticsGenと、 SchemaGenからのスキーマを入力としてSchemaGenます。

example_validator = ExampleValidator(
    statistics=statistics_gen.outputs['statistics'],
    schema=schema_gen.outputs['schema'])
context.run(example_validator)
INFO:absl:Excluding no splits because exclude_splits is not set.
INFO:absl:Running driver for ExampleValidator
INFO:absl:MetadataStore with DB connection initialized
INFO:absl:Running executor for ExampleValidator
INFO:absl:Validating schema against the computed statistics for split train.
INFO:absl:Validation complete for split train. Anomalies written to /tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/ExampleValidator/anomalies/4/train.
INFO:absl:Validating schema against the computed statistics for split eval.
INFO:absl:Validation complete for split eval. Anomalies written to /tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/ExampleValidator/anomalies/4/eval.
INFO:absl:Running publisher for ExampleValidator
INFO:absl:MetadataStore with DB connection initialized

ExampleValidator実行が終了しExampleValidator 、異常をテーブルとして視覚化できます。

context.show(example_validator.outputs['anomalies'])

異常表では、異常がないことがわかります。これは、私たちが分析した最初のデータセットであり、スキーマがそれに合わせて調整されているため、私たちが期待するものです。このスキーマを確認する必要があります。予期しないことは、データの異常を意味します。確認したら、スキーマを使用して将来のデータを保護し、ここで生成された異常を使用して、モデルのパフォーマンスをデバッグし、データが時間の経過とともにどのように変化するかを理解し、データエラーを特定できます。

変換

Transformコンポーネントは、トレーニングとサービングの両方の機能エンジニアリングを実行します。 TensorFlowTransformライブラリを使用します。

Transformは、 ExampleGenからのデータ、 ExampleGenからのスキーマ、 SchemaGenユーザー定義のTransformコードを含むモジュールを入力として受け取ります。

以下のユーザー定義の変換コードの例を見てみましょう(TensorFlow変換APIの概要については、チュートリアルを参照してください)。まず、機能エンジニアリングの定数をいくつか定義します。

_taxi_constants_module_file = 'taxi_constants.py'
%%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'
Writing taxi_constants.py

次に、生データを入力として受け取り、モデルがトレーニングできる変換された機能を返すpreprocessing_fnを記述します。

_taxi_transform_module_file = 'taxi_transform.py'
%%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)

  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)
Writing taxi_transform.py

次に、この機能エンジニアリングコードをTransformコンポーネントに渡し、それを実行してデータを変換します。

transform = Transform(
    examples=example_gen.outputs['examples'],
    schema=schema_gen.outputs['schema'],
    module_file=os.path.abspath(_taxi_transform_module_file))
context.run(transform)
INFO:absl:Running driver for Transform
INFO:absl:MetadataStore with DB connection initialized
INFO:absl:Running executor for Transform
INFO:absl:Analyze the 'train' split and transform all splits when splits_config is not set.

Warning:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tfx/components/transform/executor.py:528: Schema (from tensorflow_transform.tf_metadata.dataset_schema) is deprecated and will be removed in a future version.
Instructions for updating:
Schema is a deprecated, use schema_utils.schema_from_feature_spec to create a `Schema`

INFO:absl:Feature company has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature payment_type has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature dropoff_census_tract has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature dropoff_community_area has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature dropoff_latitude has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature dropoff_longitude has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature fare has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature pickup_census_tract has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature pickup_community_area has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature pickup_latitude has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature pickup_longitude has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature tips has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_miles has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_seconds has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_start_day has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_start_hour has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_start_month has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_start_timestamp has no shape. Setting to VarLenSparseTensor.

Warning:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow_transform/tf_utils.py:250: Tensor.experimental_ref (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use ref() instead.

INFO:absl:Feature company has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature payment_type has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature dropoff_census_tract has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature dropoff_community_area has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature dropoff_latitude has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature dropoff_longitude has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature fare has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature pickup_census_tract has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature pickup_community_area has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature pickup_latitude has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature pickup_longitude has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature tips has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_miles has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_seconds has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_start_day has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_start_hour has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_start_month has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_start_timestamp has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature company has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature payment_type has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature dropoff_census_tract has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature dropoff_community_area has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature dropoff_latitude has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature dropoff_longitude has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature fare has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature pickup_census_tract has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature pickup_community_area has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature pickup_latitude has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature pickup_longitude has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature tips has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_miles has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_seconds has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_start_day has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_start_hour has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_start_month has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_start_timestamp has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature company has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature payment_type has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature dropoff_census_tract has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature dropoff_community_area has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature dropoff_latitude has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature dropoff_longitude has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature fare has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature pickup_census_tract has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature pickup_community_area has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature pickup_latitude has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature pickup_longitude has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature tips has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_miles has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_seconds has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_start_day has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_start_hour has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_start_month has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_start_timestamp has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature company has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature payment_type has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature dropoff_census_tract has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature dropoff_community_area has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature dropoff_latitude has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature dropoff_longitude has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature fare has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature pickup_census_tract has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature pickup_community_area has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature pickup_latitude has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature pickup_longitude has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature tips has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_miles has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_seconds has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_start_day has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_start_hour has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_start_month has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_start_timestamp has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature company has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature payment_type has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature dropoff_census_tract has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature dropoff_community_area has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature dropoff_latitude has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature dropoff_longitude has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature fare has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature pickup_census_tract has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature pickup_community_area has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature pickup_latitude has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature pickup_longitude has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature tips has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_miles has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_seconds has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_start_day has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_start_hour has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_start_month has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_start_timestamp has no shape. Setting to VarLenSparseTensor.

Warning:tensorflow:TFT beam APIs accept both the TFXIO format and the instance dict format now. There is no need to set use_tfxio any more and it will be removed soon.

Warning:root:This output type hint will be ignored and not used for type-checking purposes. Typically, output type hints for a PTransform are single (or nested) types wrapped by a PCollection, PDone, or None. Got: Tuple[Dict[str, Union[NoneType, _Dataset]], Union[Dict[str, Dict[str, PCollection]], NoneType]] instead.
WARNING:root:This output type hint will be ignored and not used for type-checking purposes. Typically, output type hints for a PTransform are single (or nested) types wrapped by a PCollection, PDone, or None. Got: Tuple[Dict[str, Union[NoneType, _Dataset]], Union[Dict[str, Dict[str, PCollection]], NoneType]] instead.

Warning:tensorflow:Tensorflow version (2.3.1) found. Note that Tensorflow Transform support for TF 2.0 is currently in beta, and features such as tf.function may not work as intended. 
WARNING:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow/python/saved_model/signature_def_utils_impl.py:201: build_tensor_info (from tensorflow.python.saved_model.utils_impl) is deprecated and will be removed in a future version.
Instructions for updating:
This function will only be available through the v1 compatibility library as tf.compat.v1.saved_model.utils.build_tensor_info or tf.compat.v1.saved_model.build_tensor_info.
INFO:tensorflow:Assets added to graph.
INFO:tensorflow:No assets to write.
WARNING:tensorflow:Issue encountered when serializing tft_mapper_use.
Type is unsupported, or the types of the items don't match field type in CollectionDef. Note this is a warning and probably safe to ignore.
'Counter' object has no attribute 'name'
INFO:tensorflow:SavedModel written to: /tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/Transform/transform_graph/5/.temp_path/tftransform_tmp/2b84bdf4729f420da7592003458afbea/saved_model.pb
INFO:tensorflow:Assets added to graph.
INFO:tensorflow:No assets to write.
WARNING:tensorflow:Issue encountered when serializing tft_mapper_use.
Type is unsupported, or the types of the items don't match field type in CollectionDef. Note this is a warning and probably safe to ignore.
'Counter' object has no attribute 'name'
INFO:tensorflow:SavedModel written to: /tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/Transform/transform_graph/5/.temp_path/tftransform_tmp/41fa9edf8d3540c4bb4163ed11673ec1/saved_model.pb

INFO:absl:Feature company has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature payment_type has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature dropoff_census_tract has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature dropoff_community_area has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature dropoff_latitude has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature dropoff_longitude has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature fare has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature pickup_census_tract has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature pickup_community_area has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature pickup_latitude has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature pickup_longitude has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature tips has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_miles has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_seconds has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_start_day has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_start_hour has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_start_month has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_start_timestamp has no shape. Setting to VarLenSparseTensor.

Warning:tensorflow:Tensorflow version (2.3.1) found. Note that Tensorflow Transform support for TF 2.0 is currently in beta, and features such as tf.function may not work as intended. 

Warning:apache_beam.typehints.typehints:Ignoring send_type hint: <class 'NoneType'>
WARNING:apache_beam.typehints.typehints:Ignoring return_type hint: <class 'NoneType'>
WARNING:apache_beam.typehints.typehints:Ignoring send_type hint: <class 'NoneType'>
WARNING:apache_beam.typehints.typehints:Ignoring return_type hint: <class 'NoneType'>
WARNING:apache_beam.typehints.typehints:Ignoring send_type hint: <class 'NoneType'>
WARNING:apache_beam.typehints.typehints:Ignoring return_type hint: <class 'NoneType'>
INFO:absl:Feature company has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature payment_type has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature dropoff_census_tract has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature dropoff_community_area has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature dropoff_latitude has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature dropoff_longitude has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature fare has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature pickup_census_tract has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature pickup_community_area has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature pickup_latitude has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature pickup_longitude has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature tips has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_miles has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_seconds has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_start_day has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_start_hour has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_start_month has no shape. Setting to VarLenSparseTensor.
INFO:absl:Feature trip_start_timestamp has no shape. Setting to VarLenSparseTensor.

Warning:tensorflow:Tensorflow version (2.3.1) found. Note that Tensorflow Transform support for TF 2.0 is currently in beta, and features such as tf.function may not work as intended. 

Warning:apache_beam.typehints.typehints:Ignoring send_type hint: <class 'NoneType'>
WARNING:apache_beam.typehints.typehints:Ignoring return_type hint: <class 'NoneType'>
WARNING:apache_beam.typehints.typehints:Ignoring send_type hint: <class 'NoneType'>
WARNING:apache_beam.typehints.typehints:Ignoring return_type hint: <class 'NoneType'>
WARNING:apache_beam.typehints.typehints:Ignoring send_type hint: <class 'NoneType'>
WARNING:apache_beam.typehints.typehints:Ignoring return_type hint: <class 'NoneType'>

INFO:tensorflow:Saver not created because there are no variables in the graph to restore
INFO:tensorflow:Saver not created because there are no variables in the graph to restore
INFO:tensorflow:Assets added to graph.
INFO:tensorflow:Assets written to: /tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/Transform/transform_graph/5/.temp_path/tftransform_tmp/af6fc404ec6441879c1fa72d5be16c8b/assets
INFO:tensorflow:SavedModel written to: /tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/Transform/transform_graph/5/.temp_path/tftransform_tmp/af6fc404ec6441879c1fa72d5be16c8b/saved_model.pb
WARNING:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\013\n\tConst_2:0\022-vocab_compute_and_apply_vocabulary_vocabulary"

Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\013\n\tConst_4:0\022/vocab_compute_and_apply_vocabulary_1_vocabulary"

INFO:tensorflow:Saver not created because there are no variables in the graph to restore
WARNING:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\013\n\tConst_2:0\022-vocab_compute_and_apply_vocabulary_vocabulary"

Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\013\n\tConst_4:0\022/vocab_compute_and_apply_vocabulary_1_vocabulary"

INFO:tensorflow:Saver not created because there are no variables in the graph to restore
WARNING:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\013\n\tConst_2:0\022-vocab_compute_and_apply_vocabulary_vocabulary"

Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\013\n\tConst_4:0\022/vocab_compute_and_apply_vocabulary_1_vocabulary"

INFO:tensorflow:Saver not created because there are no variables in the graph to restore

INFO:absl:Running publisher for Transform
INFO:absl:MetadataStore with DB connection initialized

Transformの出力アーティファクトを調べてみましょう。このコンポーネントは、次の2種類の出力を生成します。

  • transform_graphは、前処理操作を実行できるグラフです(このグラフは、サービングモデルと評価モデルに含まれます)。
  • transformed_examplesは、前処理されたトレーニングおよび評価データを表します。
transform.outputs
{'transform_graph': Channel(
    type_name: TransformGraph
    artifacts: [Artifact(artifact: id: 5
type_id: 13
uri: "/tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/Transform/transform_graph/5"
custom_properties {
  key: "name"
  value {
    string_value: "transform_graph"
  }
}
custom_properties {
  key: "producer_component"
  value {
    string_value: "Transform"
  }
}
custom_properties {
  key: "state"
  value {
    string_value: "published"
  }
}
state: LIVE
, artifact_type: id: 13
name: "TransformGraph"
)]
), 'transformed_examples': Channel(
    type_name: Examples
    artifacts: [Artifact(artifact: id: 6
type_id: 5
uri: "/tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/Transform/transformed_examples/5"
properties {
  key: "split_names"
  value {
    string_value: "[\"train\", \"eval\"]"
  }
}
custom_properties {
  key: "name"
  value {
    string_value: "transformed_examples"
  }
}
custom_properties {
  key: "producer_component"
  value {
    string_value: "Transform"
  }
}
custom_properties {
  key: "state"
  value {
    string_value: "published"
  }
}
state: LIVE
, artifact_type: id: 5
name: "Examples"
properties {
  key: "span"
  value: INT
}
properties {
  key: "split_names"
  value: STRING
}
properties {
  key: "version"
  value: INT
}
)]
), 'updated_analyzer_cache': Channel(
    type_name: TransformCache
    artifacts: [Artifact(artifact: id: 7
type_id: 14
uri: "/tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/Transform/updated_analyzer_cache/5"
custom_properties {
  key: "name"
  value {
    string_value: "updated_analyzer_cache"
  }
}
custom_properties {
  key: "producer_component"
  value {
    string_value: "Transform"
  }
}
custom_properties {
  key: "state"
  value {
    string_value: "published"
  }
}
state: LIVE
, artifact_type: id: 14
name: "TransformCache"
)]
)}

transform_graphアーティファクトをのぞいてみましょう。これは、3つのサブディレクトリを含むディレクトリを指します。

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

transformed_metadataサブディレクトリには、前処理されたデータのスキーマが含まれています。 transform_fnサブディレクトリには、実際の前処理グラフが含まれています。 metadataサブディレクトリには、元のデータのスキーマが含まれています。

また、最初の3つの変換された例を見ることができます。

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

# 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")

# Iterate over the first 3 records and decode them.
for tfrecord in dataset.take(3):
  serialized_example = tfrecord.numpy()
  example = tf.train.Example()
  example.ParseFromString(serialized_example)
  pp.pprint(example)
features {
  feature {
    key: "company_xf"
    value {
      int64_list {
        value: 8
      }
    }
  }
  feature {
    key: "dropoff_census_tract_xf"
    value {
      int64_list {
        value: 0
      }
    }
  }
  feature {
    key: "dropoff_community_area_xf"
    value {
      int64_list {
        value: 0
      }
    }
  }
  feature {
    key: "dropoff_latitude_xf"
    value {
      int64_list {
        value: 0
      }
    }
  }
  feature {
    key: "dropoff_longitude_xf"
    value {
      int64_list {
        value: 9
      }
    }
  }
  feature {
    key: "fare_xf"
    value {
      float_list {
        value: 0.06106060370802879
      }
    }
  }
  feature {
    key: "payment_type_xf"
    value {
      int64_list {
        value: 1
      }
    }
  }
  feature {
    key: "pickup_census_tract_xf"
    value {
      int64_list {
        value: 0
      }
    }
  }
  feature {
    key: "pickup_community_area_xf"
    value {
      int64_list {
        value: 0
      }
    }
  }
  feature {
    key: "pickup_latitude_xf"
    value {
      int64_list {
        value: 0
      }
    }
  }
  feature {
    key: "pickup_longitude_xf"
    value {
      int64_list {
        value: 9
      }
    }
  }
  feature {
    key: "tips_xf"
    value {
      int64_list {
        value: 0
      }
    }
  }
  feature {
    key: "trip_miles_xf"
    value {
      float_list {
        value: -0.15886740386486053
      }
    }
  }
  feature {
    key: "trip_seconds_xf"
    value {
      float_list {
        value: -0.7118487358093262
      }
    }
  }
  feature {
    key: "trip_start_day_xf"
    value {
      int64_list {
        value: 6
      }
    }
  }
  feature {
    key: "trip_start_hour_xf"
    value {
      int64_list {
        value: 19
      }
    }
  }
  feature {
    key: "trip_start_month_xf"
    value {
      int64_list {
        value: 5
      }
    }
  }
}

features {
  feature {
    key: "company_xf"
    value {
      int64_list {
        value: 0
      }
    }
  }
  feature {
    key: "dropoff_census_tract_xf"
    value {
      int64_list {
        value: 0
      }
    }
  }
  feature {
    key: "dropoff_community_area_xf"
    value {
      int64_list {
        value: 0
      }
    }
  }
  feature {
    key: "dropoff_latitude_xf"
    value {
      int64_list {
        value: 0
      }
    }
  }
  feature {
    key: "dropoff_longitude_xf"
    value {
      int64_list {
        value: 9
      }
    }
  }
  feature {
    key: "fare_xf"
    value {
      float_list {
        value: 1.2521241903305054
      }
    }
  }
  feature {
    key: "payment_type_xf"
    value {
      int64_list {
        value: 0
      }
    }
  }
  feature {
    key: "pickup_census_tract_xf"
    value {
      int64_list {
        value: 0
      }
    }
  }
  feature {
    key: "pickup_community_area_xf"
    value {
      int64_list {
        value: 60
      }
    }
  }
  feature {
    key: "pickup_latitude_xf"
    value {
      int64_list {
        value: 0
      }
    }
  }
  feature {
    key: "pickup_longitude_xf"
    value {
      int64_list {
        value: 3
      }
    }
  }
  feature {
    key: "tips_xf"
    value {
      int64_list {
        value: 0
      }
    }
  }
  feature {
    key: "trip_miles_xf"
    value {
      float_list {
        value: 0.532160758972168
      }
    }
  }
  feature {
    key: "trip_seconds_xf"
    value {
      float_list {
        value: 0.5509493350982666
      }
    }
  }
  feature {
    key: "trip_start_day_xf"
    value {
      int64_list {
        value: 3
      }
    }
  }
  feature {
    key: "trip_start_hour_xf"
    value {
      int64_list {
        value: 2
      }
    }
  }
  feature {
    key: "trip_start_month_xf"
    value {
      int64_list {
        value: 10
      }
    }
  }
}

features {
  feature {
    key: "company_xf"
    value {
      int64_list {
        value: 48
      }
    }
  }
  feature {
    key: "dropoff_census_tract_xf"
    value {
      int64_list {
        value: 0
      }
    }
  }
  feature {
    key: "dropoff_community_area_xf"
    value {
      int64_list {
        value: 0
      }
    }
  }
  feature {
    key: "dropoff_latitude_xf"
    value {
      int64_list {
        value: 0
      }
    }
  }
  feature {
    key: "dropoff_longitude_xf"
    value {
      int64_list {
        value: 9
      }
    }
  }
  feature {
    key: "fare_xf"
    value {
      float_list {
        value: 0.3873794972896576
      }
    }
  }
  feature {
    key: "payment_type_xf"
    value {
      int64_list {
        value: 0
      }
    }
  }
  feature {
    key: "pickup_census_tract_xf"
    value {
      int64_list {
        value: 0
      }
    }
  }
  feature {
    key: "pickup_community_area_xf"
    value {
      int64_list {
        value: 13
      }
    }
  }
  feature {
    key: "pickup_latitude_xf"
    value {
      int64_list {
        value: 9
      }
    }
  }
  feature {
    key: "pickup_longitude_xf"
    value {
      int64_list {
        value: 0
      }
    }
  }
  feature {
    key: "tips_xf"
    value {
      int64_list {
        value: 0
      }
    }
  }
  feature {
    key: "trip_miles_xf"
    value {
      float_list {
        value: 0.21955278515815735
      }
    }
  }
  feature {
    key: "trip_seconds_xf"
    value {
      float_list {
        value: 0.0019067145185545087
      }
    }
  }
  feature {
    key: "trip_start_day_xf"
    value {
      int64_list {
        value: 3
      }
    }
  }
  feature {
    key: "trip_start_hour_xf"
    value {
      int64_list {
        value: 12
      }
    }
  }
  feature {
    key: "trip_start_month_xf"
    value {
      int64_list {
        value: 11
      }
    }
  }
}


Transformコンポーネントがデータをフィーチャに変換した後、次のステップはモデルをトレーニングすることです。

トレーナー

Trainerコンポーネントを使用すると、TensorFlowで定義されていることのモデルを訓練(のいずれかで見積もりのAPIやKerasのAPIを使用しますmodel_to_estimator )。

Trainerからの入力としてスキーマを取りSchemaGen 、変換されたデータとグラフからTransform 、トレーニングパラメータ、ならびにユーザ定義のモデルコードを含むモジュール。

以下のユーザー定義モデルコードの例を見てみましょう(TensorFlow Estimator APIの概要については、チュートリアルを参照してください)。

_taxi_trainer_module_file = 'taxi_trainer.py'
%%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
from tfx_bsl.tfxio import dataset_options

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 _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_graph, schema):
  """Build the serving in inputs.
  Args:
    tf_transform_graph: 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_graph.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_graph, schema):
  """Build everything needed for the tf-model-analysis to run the model.
  Args:
    tf_transform_graph: 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.compat.v1.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.io.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_graph.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(file_pattern, data_accessor, tf_transform_output, batch_size=200):
  """Generates features and label for tuning/training.

  Args:
    file_pattern: List of paths or patterns of input tfrecord files.
    data_accessor: DataAccessor for converting input to RecordBatch.
    tf_transform_output: A TFTransformOutput.
    batch_size: representing the number of consecutive elements of returned
      dataset to combine in a single batch

  Returns:
    A dataset that contains (features, indices) tuple where features is a
      dictionary of Tensors, and indices is a single Tensor of label indices.
  """
  return data_accessor.tf_dataset_factory(
      file_pattern,
      dataset_options.TensorFlowDatasetOptions(
          batch_size=batch_size, label_key=_transformed_name(_LABEL_KEY)),
      tf_transform_output.transformed_metadata.schema)


# TFX will call this function
def trainer_fn(trainer_fn_args, schema):
  """Build the estimator using the high level API.
  Args:
    trainer_fn_args: Holds args 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_graph = tft.TFTransformOutput(trainer_fn_args.transform_output)

  train_input_fn = lambda: _input_fn(  # pylint: disable=g-long-lambda
      trainer_fn_args.train_files,
      trainer_fn_args.data_accessor,
      tf_transform_graph,
      batch_size=train_batch_size)

  eval_input_fn = lambda: _input_fn(  # pylint: disable=g-long-lambda
      trainer_fn_args.eval_files,
      trainer_fn_args.data_accessor,
      tf_transform_graph,
      batch_size=eval_batch_size)

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

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

  exporter = tf.estimator.FinalExporter('chicago-taxi', serving_receiver_fn)
  eval_spec = tf.estimator.EvalSpec(
      eval_input_fn,
      steps=trainer_fn_args.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=trainer_fn_args.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=trainer_fn_args.base_model)

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

  return {
      'estimator': estimator,
      'train_spec': train_spec,
      'eval_spec': eval_spec,
      'eval_input_receiver_fn': receiver_fn
  }
Writing taxi_trainer.py

次に、このモデルコードをTrainerコンポーネントに渡し、それを実行してモデルをトレーニングします。

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)
INFO:absl:Running driver for Trainer
INFO:absl:MetadataStore with DB connection initialized
INFO:absl:Running executor for Trainer
INFO:absl:Train on the 'train' split when train_args.splits is not set.
INFO:absl:Evaluate on the 'eval' split when eval_args.splits is not set.
WARNING:absl:Examples artifact does not have payload_format custom property. Falling back to FORMAT_TF_EXAMPLE
WARNING:absl:Examples artifact does not have payload_format custom property. Falling back to FORMAT_TF_EXAMPLE

INFO:tensorflow:Using config: {'_model_dir': '/tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/Trainer/model_run/6/serving_model_dir', '_tf_random_seed': None, '_save_summary_steps': 100, '_save_checkpoints_steps': 999, '_save_checkpoints_secs': None, '_session_config': allow_soft_placement: true
graph_options {
  rewrite_options {
    meta_optimizer_iterations: ONE
  }
}
, '_keep_checkpoint_max': 1, '_keep_checkpoint_every_n_hours': 10000, '_log_step_count_steps': 100, '_train_distribute': None, '_device_fn': None, '_protocol': None, '_eval_distribute': None, '_experimental_distribute': None, '_experimental_max_worker_delay_secs': None, '_session_creation_timeout_secs': 7200, '_service': None, '_cluster_spec': ClusterSpec({}), '_task_type': 'worker', '_task_id': 0, '_global_id_in_cluster': 0, '_master': '', '_evaluation_master': '', '_is_chief': True, '_num_ps_replicas': 0, '_num_worker_replicas': 1}

INFO:absl:Training model.

INFO:tensorflow:Not using Distribute Coordinator.
INFO:tensorflow:Running training and evaluation locally (non-distributed).
INFO:tensorflow:Start train and evaluate loop. The evaluate will happen after every checkpoint. Checkpoint frequency is determined based on RunConfig arguments: save_checkpoints_steps 999 or save_checkpoints_secs None.
WARNING:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow/python/training/training_util.py:236: Variable.initialized_value (from tensorflow.python.ops.variables) is deprecated and will be removed in a future version.
Instructions for updating:
Use Variable.read_value. Variables in 2.X are initialized automatically both in eager and graph (inside tf.defun) contexts.

INFO:absl:Feature company_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature dropoff_census_tract_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature dropoff_community_area_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature dropoff_latitude_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature dropoff_longitude_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature fare_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature payment_type_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature pickup_census_tract_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature pickup_community_area_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature pickup_latitude_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature pickup_longitude_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature tips_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature trip_miles_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature trip_seconds_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature trip_start_day_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature trip_start_hour_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature trip_start_month_xf has a shape . Setting to DenseTensor.

INFO:tensorflow:Calling model_fn.
WARNING:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow_estimator/python/estimator/canned/linear.py:1481: Layer.add_variable (from tensorflow.python.keras.engine.base_layer_v1) is deprecated and will be removed in a future version.
Instructions for updating:
Please use `layer.add_weight` method instead.
WARNING:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow/python/keras/optimizer_v2/adagrad.py:83: calling Constant.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.
Instructions for updating:
Call initializer instance with the dtype argument instead of passing it to the constructor
INFO:tensorflow:Done calling model_fn.
INFO:tensorflow:Create CheckpointSaverHook.
INFO:tensorflow:Graph was finalized.
INFO:tensorflow:Running local_init_op.
INFO:tensorflow:Done running local_init_op.
INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 0...
INFO:tensorflow:Saving checkpoints for 0 into /tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/Trainer/model_run/6/serving_model_dir/model.ckpt.
INFO:tensorflow:Calling checkpoint listeners after saving checkpoint 0...
INFO:tensorflow:loss = 0.6974667, step = 0
INFO:tensorflow:global_step/sec: 89.1231
INFO:tensorflow:loss = 0.5732481, step = 100 (1.123 sec)
INFO:tensorflow:global_step/sec: 113.474
INFO:tensorflow:loss = 0.5176774, step = 200 (0.881 sec)
INFO:tensorflow:global_step/sec: 114.63
INFO:tensorflow:loss = 0.5562607, step = 300 (0.872 sec)
INFO:tensorflow:global_step/sec: 113.5
INFO:tensorflow:loss = 0.53873014, step = 400 (0.881 sec)
INFO:tensorflow:global_step/sec: 111.799
INFO:tensorflow:loss = 0.44045067, step = 500 (0.894 sec)
INFO:tensorflow:global_step/sec: 113.062
INFO:tensorflow:loss = 0.57715523, step = 600 (0.885 sec)
INFO:tensorflow:global_step/sec: 112.051
INFO:tensorflow:loss = 0.46877265, step = 700 (0.892 sec)
INFO:tensorflow:global_step/sec: 112.388
INFO:tensorflow:loss = 0.51078546, step = 800 (0.890 sec)
INFO:tensorflow:global_step/sec: 111.415
INFO:tensorflow:loss = 0.4560148, step = 900 (0.898 sec)
INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 999...
INFO:tensorflow:Saving checkpoints for 999 into /tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/Trainer/model_run/6/serving_model_dir/model.ckpt.
WARNING:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow/python/training/saver.py:971: remove_checkpoint (from tensorflow.python.training.checkpoint_management) is deprecated and will be removed in a future version.
Instructions for updating:
Use standard file APIs to delete files with this prefix.
INFO:tensorflow:Calling checkpoint listeners after saving checkpoint 999...

INFO:absl:Feature company_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature dropoff_census_tract_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature dropoff_community_area_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature dropoff_latitude_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature dropoff_longitude_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature fare_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature payment_type_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature pickup_census_tract_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature pickup_community_area_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature pickup_latitude_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature pickup_longitude_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature tips_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature trip_miles_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature trip_seconds_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature trip_start_day_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature trip_start_hour_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature trip_start_month_xf has a shape . Setting to DenseTensor.

INFO:tensorflow:Calling model_fn.
INFO:tensorflow:Done calling model_fn.
INFO:tensorflow:Starting evaluation at 2020-11-26T10:14:00Z
INFO:tensorflow:Graph was finalized.
INFO:tensorflow:Restoring parameters from /tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/Trainer/model_run/6/serving_model_dir/model.ckpt-999
INFO:tensorflow:Running local_init_op.
INFO:tensorflow:Done running local_init_op.
INFO:tensorflow:Evaluation [500/5000]
INFO:tensorflow:Evaluation [1000/5000]
INFO:tensorflow:Evaluation [1500/5000]
INFO:tensorflow:Evaluation [2000/5000]
INFO:tensorflow:Evaluation [2500/5000]
INFO:tensorflow:Evaluation [3000/5000]
INFO:tensorflow:Evaluation [3500/5000]
INFO:tensorflow:Evaluation [4000/5000]
INFO:tensorflow:Evaluation [4500/5000]
INFO:tensorflow:Evaluation [5000/5000]
INFO:tensorflow:Inference Time : 46.48948s
INFO:tensorflow:Finished evaluation at 2020-11-26-10:14:46
INFO:tensorflow:Saving dict for global step 999: accuracy = 0.77121, accuracy_baseline = 0.77121, auc = 0.9247545, auc_precision_recall = 0.66692716, average_loss = 0.46251872, global_step = 999, label/mean = 0.22879, loss = 0.46251866, precision = 0.0, prediction/mean = 0.2535291, recall = 0.0
INFO:tensorflow:Saving 'checkpoint_path' summary for global step 999: /tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/Trainer/model_run/6/serving_model_dir/model.ckpt-999
INFO:tensorflow:global_step/sec: 2.043
INFO:tensorflow:loss = 0.3749024, step = 1000 (48.948 sec)
INFO:tensorflow:global_step/sec: 109.709
INFO:tensorflow:loss = 0.4592988, step = 1100 (0.912 sec)
INFO:tensorflow:global_step/sec: 112.449
INFO:tensorflow:loss = 0.37520203, step = 1200 (0.890 sec)
INFO:tensorflow:global_step/sec: 109.812
INFO:tensorflow:loss = 0.38372535, step = 1300 (0.910 sec)
INFO:tensorflow:global_step/sec: 113.247
INFO:tensorflow:loss = 0.4365883, step = 1400 (0.883 sec)
INFO:tensorflow:global_step/sec: 114.602
INFO:tensorflow:loss = 0.42457563, step = 1500 (0.873 sec)
INFO:tensorflow:global_step/sec: 115.115
INFO:tensorflow:loss = 0.38821325, step = 1600 (0.869 sec)
INFO:tensorflow:global_step/sec: 114.471
INFO:tensorflow:loss = 0.4025802, step = 1700 (0.874 sec)
INFO:tensorflow:global_step/sec: 114.604
INFO:tensorflow:loss = 0.50898427, step = 1800 (0.873 sec)
INFO:tensorflow:global_step/sec: 115.29
INFO:tensorflow:loss = 0.39604157, step = 1900 (0.868 sec)
INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 1998...
INFO:tensorflow:Saving checkpoints for 1998 into /tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/Trainer/model_run/6/serving_model_dir/model.ckpt.
INFO:tensorflow:Calling checkpoint listeners after saving checkpoint 1998...
INFO:tensorflow:Skip the current checkpoint eval due to throttle secs (600 secs).
INFO:tensorflow:global_step/sec: 100.896
INFO:tensorflow:loss = 0.4355023, step = 2000 (0.991 sec)
INFO:tensorflow:global_step/sec: 114.377
INFO:tensorflow:loss = 0.4315641, step = 2100 (0.874 sec)
INFO:tensorflow:global_step/sec: 113.536
INFO:tensorflow:loss = 0.34944555, step = 2200 (0.881 sec)
INFO:tensorflow:global_step/sec: 113.708
INFO:tensorflow:loss = 0.43738118, step = 2300 (0.879 sec)
INFO:tensorflow:global_step/sec: 115.111
INFO:tensorflow:loss = 0.47878623, step = 2400 (0.869 sec)
INFO:tensorflow:global_step/sec: 112.33
INFO:tensorflow:loss = 0.383889, step = 2500 (0.891 sec)
INFO:tensorflow:global_step/sec: 113.464
INFO:tensorflow:loss = 0.35396174, step = 2600 (0.881 sec)
INFO:tensorflow:global_step/sec: 112.511
INFO:tensorflow:loss = 0.3468891, step = 2700 (0.889 sec)
INFO:tensorflow:global_step/sec: 113.298
INFO:tensorflow:loss = 0.38933015, step = 2800 (0.883 sec)
INFO:tensorflow:global_step/sec: 114.633
INFO:tensorflow:loss = 0.34905306, step = 2900 (0.872 sec)
INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 2997...
INFO:tensorflow:Saving checkpoints for 2997 into /tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/Trainer/model_run/6/serving_model_dir/model.ckpt.
INFO:tensorflow:Calling checkpoint listeners after saving checkpoint 2997...
INFO:tensorflow:Skip the current checkpoint eval due to throttle secs (600 secs).
INFO:tensorflow:global_step/sec: 100.777
INFO:tensorflow:loss = 0.42350882, step = 3000 (0.992 sec)
INFO:tensorflow:global_step/sec: 113.785
INFO:tensorflow:loss = 0.31562096, step = 3100 (0.879 sec)
INFO:tensorflow:global_step/sec: 113.34
INFO:tensorflow:loss = 0.42950398, step = 3200 (0.882 sec)
INFO:tensorflow:global_step/sec: 114.675
INFO:tensorflow:loss = 0.47113928, step = 3300 (0.872 sec)
INFO:tensorflow:global_step/sec: 114.508
INFO:tensorflow:loss = 0.41468287, step = 3400 (0.873 sec)
INFO:tensorflow:global_step/sec: 115.75
INFO:tensorflow:loss = 0.31615996, step = 3500 (0.864 sec)
INFO:tensorflow:global_step/sec: 114.195
INFO:tensorflow:loss = 0.4714353, step = 3600 (0.876 sec)
INFO:tensorflow:global_step/sec: 114.797
INFO:tensorflow:loss = 0.30707058, step = 3700 (0.871 sec)
INFO:tensorflow:global_step/sec: 114.767
INFO:tensorflow:loss = 0.3783667, step = 3800 (0.871 sec)
INFO:tensorflow:global_step/sec: 114.016
INFO:tensorflow:loss = 0.34137535, step = 3900 (0.877 sec)
INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 3996...
INFO:tensorflow:Saving checkpoints for 3996 into /tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/Trainer/model_run/6/serving_model_dir/model.ckpt.
INFO:tensorflow:Calling checkpoint listeners after saving checkpoint 3996...
INFO:tensorflow:Skip the current checkpoint eval due to throttle secs (600 secs).
INFO:tensorflow:global_step/sec: 100.197
INFO:tensorflow:loss = 0.45167357, step = 4000 (0.998 sec)
INFO:tensorflow:global_step/sec: 114.295
INFO:tensorflow:loss = 0.36682805, step = 4100 (0.875 sec)
INFO:tensorflow:global_step/sec: 112.865
INFO:tensorflow:loss = 0.37716842, step = 4200 (0.886 sec)
INFO:tensorflow:global_step/sec: 114.446
INFO:tensorflow:loss = 0.34928334, step = 4300 (0.874 sec)
INFO:tensorflow:global_step/sec: 113.651
INFO:tensorflow:loss = 0.46821588, step = 4400 (0.880 sec)
INFO:tensorflow:global_step/sec: 111.894
INFO:tensorflow:loss = 0.42282277, step = 4500 (0.894 sec)
INFO:tensorflow:global_step/sec: 113.436
INFO:tensorflow:loss = 0.34230947, step = 4600 (0.883 sec)
INFO:tensorflow:global_step/sec: 112.371
INFO:tensorflow:loss = 0.40548354, step = 4700 (0.889 sec)
INFO:tensorflow:global_step/sec: 113.867
INFO:tensorflow:loss = 0.3861308, step = 4800 (0.878 sec)
INFO:tensorflow:global_step/sec: 112.406
INFO:tensorflow:loss = 0.3875846, step = 4900 (0.890 sec)
INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 4995...
INFO:tensorflow:Saving checkpoints for 4995 into /tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/Trainer/model_run/6/serving_model_dir/model.ckpt.
INFO:tensorflow:Calling checkpoint listeners after saving checkpoint 4995...
INFO:tensorflow:Skip the current checkpoint eval due to throttle secs (600 secs).
INFO:tensorflow:global_step/sec: 99.7081
INFO:tensorflow:loss = 0.44678396, step = 5000 (1.003 sec)
INFO:tensorflow:global_step/sec: 112.912
INFO:tensorflow:loss = 0.39096385, step = 5100 (0.886 sec)
INFO:tensorflow:global_step/sec: 113.011
INFO:tensorflow:loss = 0.3414794, step = 5200 (0.885 sec)
INFO:tensorflow:global_step/sec: 114.988
INFO:tensorflow:loss = 0.3385579, step = 5300 (0.869 sec)
INFO:tensorflow:global_step/sec: 113.642
INFO:tensorflow:loss = 0.32704902, step = 5400 (0.880 sec)
INFO:tensorflow:global_step/sec: 113.67
INFO:tensorflow:loss = 0.39469784, step = 5500 (0.880 sec)
INFO:tensorflow:global_step/sec: 114.248
INFO:tensorflow:loss = 0.33442765, step = 5600 (0.875 sec)
INFO:tensorflow:global_step/sec: 114.85
INFO:tensorflow:loss = 0.3017143, step = 5700 (0.871 sec)
INFO:tensorflow:global_step/sec: 114.052
INFO:tensorflow:loss = 0.33482796, step = 5800 (0.877 sec)
INFO:tensorflow:global_step/sec: 113.413
INFO:tensorflow:loss = 0.42112976, step = 5900 (0.882 sec)
INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 5994...
INFO:tensorflow:Saving checkpoints for 5994 into /tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/Trainer/model_run/6/serving_model_dir/model.ckpt.
INFO:tensorflow:Calling checkpoint listeners after saving checkpoint 5994...
INFO:tensorflow:Skip the current checkpoint eval due to throttle secs (600 secs).
INFO:tensorflow:global_step/sec: 98.5739
INFO:tensorflow:loss = 0.3670102, step = 6000 (1.015 sec)
INFO:tensorflow:global_step/sec: 114.786
INFO:tensorflow:loss = 0.33206683, step = 6100 (0.871 sec)
INFO:tensorflow:global_step/sec: 112.258
INFO:tensorflow:loss = 0.3649478, step = 6200 (0.891 sec)
INFO:tensorflow:global_step/sec: 113.265
INFO:tensorflow:loss = 0.34351104, step = 6300 (0.884 sec)
INFO:tensorflow:global_step/sec: 113.556
INFO:tensorflow:loss = 0.33417398, step = 6400 (0.880 sec)
INFO:tensorflow:global_step/sec: 115.112
INFO:tensorflow:loss = 0.40121427, step = 6500 (0.869 sec)
INFO:tensorflow:global_step/sec: 112.671
INFO:tensorflow:loss = 0.34591922, step = 6600 (0.888 sec)
INFO:tensorflow:global_step/sec: 114.971
INFO:tensorflow:loss = 0.34938964, step = 6700 (0.870 sec)
INFO:tensorflow:global_step/sec: 114.675
INFO:tensorflow:loss = 0.37972444, step = 6800 (0.872 sec)
INFO:tensorflow:global_step/sec: 114.236
INFO:tensorflow:loss = 0.37977144, step = 6900 (0.875 sec)
INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 6993...
INFO:tensorflow:Saving checkpoints for 6993 into /tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/Trainer/model_run/6/serving_model_dir/model.ckpt.
INFO:tensorflow:Calling checkpoint listeners after saving checkpoint 6993...
INFO:tensorflow:Skip the current checkpoint eval due to throttle secs (600 secs).
INFO:tensorflow:global_step/sec: 99.2694
INFO:tensorflow:loss = 0.35126358, step = 7000 (1.007 sec)
INFO:tensorflow:global_step/sec: 112.529
INFO:tensorflow:loss = 0.37536883, step = 7100 (0.889 sec)
INFO:tensorflow:global_step/sec: 114.702
INFO:tensorflow:loss = 0.38491726, step = 7200 (0.872 sec)
INFO:tensorflow:global_step/sec: 114.154
INFO:tensorflow:loss = 0.34859103, step = 7300 (0.876 sec)
INFO:tensorflow:global_step/sec: 113.878
INFO:tensorflow:loss = 0.2851309, step = 7400 (0.878 sec)
INFO:tensorflow:global_step/sec: 115.684
INFO:tensorflow:loss = 0.33018833, step = 7500 (0.864 sec)
INFO:tensorflow:global_step/sec: 115.05
INFO:tensorflow:loss = 0.2911943, step = 7600 (0.869 sec)
INFO:tensorflow:global_step/sec: 114.228
INFO:tensorflow:loss = 0.34445795, step = 7700 (0.875 sec)
INFO:tensorflow:global_step/sec: 112.949
INFO:tensorflow:loss = 0.3777662, step = 7800 (0.885 sec)
INFO:tensorflow:global_step/sec: 114.814
INFO:tensorflow:loss = 0.3525071, step = 7900 (0.871 sec)
INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 7992...
INFO:tensorflow:Saving checkpoints for 7992 into /tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/Trainer/model_run/6/serving_model_dir/model.ckpt.
INFO:tensorflow:Calling checkpoint listeners after saving checkpoint 7992...
INFO:tensorflow:Skip the current checkpoint eval due to throttle secs (600 secs).
INFO:tensorflow:global_step/sec: 100.595
INFO:tensorflow:loss = 0.31738895, step = 8000 (0.995 sec)
INFO:tensorflow:global_step/sec: 115.258
INFO:tensorflow:loss = 0.32818204, step = 8100 (0.867 sec)
INFO:tensorflow:global_step/sec: 114.606
INFO:tensorflow:loss = 0.3743958, step = 8200 (0.872 sec)
INFO:tensorflow:global_step/sec: 114.643
INFO:tensorflow:loss = 0.34712324, step = 8300 (0.872 sec)
INFO:tensorflow:global_step/sec: 115.182
INFO:tensorflow:loss = 0.35043937, step = 8400 (0.868 sec)
INFO:tensorflow:global_step/sec: 114.304
INFO:tensorflow:loss = 0.37599805, step = 8500 (0.875 sec)
INFO:tensorflow:global_step/sec: 112.461
INFO:tensorflow:loss = 0.34265774, step = 8600 (0.889 sec)
INFO:tensorflow:global_step/sec: 114.598
INFO:tensorflow:loss = 0.35895196, step = 8700 (0.873 sec)
INFO:tensorflow:global_step/sec: 114.452
INFO:tensorflow:loss = 0.33054015, step = 8800 (0.874 sec)
INFO:tensorflow:global_step/sec: 115.018
INFO:tensorflow:loss = 0.30547625, step = 8900 (0.869 sec)
INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 8991...
INFO:tensorflow:Saving checkpoints for 8991 into /tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/Trainer/model_run/6/serving_model_dir/model.ckpt.
INFO:tensorflow:Calling checkpoint listeners after saving checkpoint 8991...
INFO:tensorflow:Skip the current checkpoint eval due to throttle secs (600 secs).
INFO:tensorflow:global_step/sec: 101.705
INFO:tensorflow:loss = 0.3225851, step = 9000 (0.983 sec)
INFO:tensorflow:global_step/sec: 114.576
INFO:tensorflow:loss = 0.34777793, step = 9100 (0.873 sec)
INFO:tensorflow:global_step/sec: 115.056
INFO:tensorflow:loss = 0.3121646, step = 9200 (0.869 sec)
INFO:tensorflow:global_step/sec: 114.867
INFO:tensorflow:loss = 0.29584178, step = 9300 (0.871 sec)
INFO:tensorflow:global_step/sec: 112.136
INFO:tensorflow:loss = 0.34916228, step = 9400 (0.892 sec)
INFO:tensorflow:global_step/sec: 112.682
INFO:tensorflow:loss = 0.37707886, step = 9500 (0.887 sec)
INFO:tensorflow:global_step/sec: 111.734
INFO:tensorflow:loss = 0.3262028, step = 9600 (0.895 sec)
INFO:tensorflow:global_step/sec: 110.884
INFO:tensorflow:loss = 0.4361206, step = 9700 (0.902 sec)
INFO:tensorflow:global_step/sec: 111.58
INFO:tensorflow:loss = 0.24492769, step = 9800 (0.896 sec)
INFO:tensorflow:global_step/sec: 113.033
INFO:tensorflow:loss = 0.320422, step = 9900 (0.885 sec)
INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 9990...
INFO:tensorflow:Saving checkpoints for 9990 into /tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/Trainer/model_run/6/serving_model_dir/model.ckpt.
INFO:tensorflow:Calling checkpoint listeners after saving checkpoint 9990...
INFO:tensorflow:Skip the current checkpoint eval due to throttle secs (600 secs).
INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 10000...
INFO:tensorflow:Saving checkpoints for 10000 into /tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/Trainer/model_run/6/serving_model_dir/model.ckpt.
INFO:tensorflow:Calling checkpoint listeners after saving checkpoint 10000...
INFO:tensorflow:Skip the current checkpoint eval due to throttle secs (600 secs).

INFO:absl:Feature company_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature dropoff_census_tract_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature dropoff_community_area_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature dropoff_latitude_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature dropoff_longitude_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature fare_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature payment_type_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature pickup_census_tract_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature pickup_community_area_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature pickup_latitude_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature pickup_longitude_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature tips_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature trip_miles_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature trip_seconds_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature trip_start_day_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature trip_start_hour_xf has a shape . Setting to DenseTensor.
INFO:absl:Feature trip_start_month_xf has a shape . Setting to DenseTensor.

INFO:tensorflow:Calling model_fn.
INFO:tensorflow:Done calling model_fn.
INFO:tensorflow:Starting evaluation at 2020-11-26T10:16:08Z
INFO:tensorflow:Graph was finalized.
INFO:tensorflow:Restoring parameters from /tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/Trainer/model_run/6/serving_model_dir/model.ckpt-10000
INFO:tensorflow:Running local_init_op.
INFO:tensorflow:Done running local_init_op.
INFO:tensorflow:Evaluation [500/5000]
INFO:tensorflow:Evaluation [1000/5000]
INFO:tensorflow:Evaluation [1500/5000]
INFO:tensorflow:Evaluation [2000/5000]
INFO:tensorflow:Evaluation [2500/5000]
INFO:tensorflow:Evaluation [3000/5000]
INFO:tensorflow:Evaluation [3500/5000]
INFO:tensorflow:Evaluation [4000/5000]
INFO:tensorflow:Evaluation [4500/5000]
INFO:tensorflow:Evaluation [5000/5000]
INFO:tensorflow:Inference Time : 44.32158s
INFO:tensorflow:Finished evaluation at 2020-11-26-10:16:53
INFO:tensorflow:Saving dict for global step 10000: accuracy = 0.785505, accuracy_baseline = 0.771185, auc = 0.9335164, auc_precision_recall = 0.703921, average_loss = 0.34539613, global_step = 10000, label/mean = 0.228815, loss = 0.34539708, precision = 0.6922148, prediction/mean = 0.23044644, recall = 0.112689294
INFO:tensorflow:Saving 'checkpoint_path' summary for global step 10000: /tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/Trainer/model_run/6/serving_model_dir/model.ckpt-10000
INFO:tensorflow:Performing the final export in the end of training.
WARNING:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\013\n\tConst_2:0\022-vocab_compute_and_apply_vocabulary_vocabulary"

Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\013\n\tConst_4:0\022/vocab_compute_and_apply_vocabulary_1_vocabulary"

INFO:tensorflow:Saver not created because there are no variables in the graph to restore
INFO:tensorflow:Calling model_fn.
INFO:tensorflow:Done calling model_fn.
INFO:tensorflow:Signatures INCLUDED in export for Classify: ['serving_default', 'classification']
INFO:tensorflow:Signatures INCLUDED in export for Regress: ['regression']
INFO:tensorflow:Signatures INCLUDED in export for Predict: ['predict']
INFO:tensorflow:Signatures INCLUDED in export for Train: None
INFO:tensorflow:Signatures INCLUDED in export for Eval: None
INFO:tensorflow:Restoring parameters from /tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/Trainer/model_run/6/serving_model_dir/model.ckpt-10000
INFO:tensorflow:Assets added to graph.
INFO:tensorflow:Assets written to: /tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/Trainer/model_run/6/serving_model_dir/export/chicago-taxi/temp-1606385813/assets
INFO:tensorflow:SavedModel written to: /tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/Trainer/model_run/6/serving_model_dir/export/chicago-taxi/temp-1606385813/saved_model.pb
INFO:tensorflow:Loss for final step: 0.373849.

INFO:absl:Training complete. Model written to /tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/Trainer/model_run/6/serving_model_dir. ModelRun written to /tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/Trainer/model_run/6
INFO:absl:Exporting eval_savedmodel for TFMA.

Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\013\n\tConst_2:0\022-vocab_compute_and_apply_vocabulary_vocabulary"

Warning:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef"
value: "\n\013\n\tConst_4:0\022/vocab_compute_and_apply_vocabulary_1_vocabulary"

INFO:tensorflow:Saver not created because there are no variables in the graph to restore
INFO:tensorflow:Calling model_fn.
INFO:tensorflow:Done calling model_fn.
INFO:tensorflow:Signatures INCLUDED in export for Classify: None
INFO:tensorflow:Signatures INCLUDED in export for Regress: None
INFO:tensorflow:Signatures INCLUDED in export for Predict: None
INFO:tensorflow:Signatures INCLUDED in export for Train: None
INFO:tensorflow:Signatures INCLUDED in export for Eval: ['eval']
WARNING:tensorflow:Export includes no default signature!
INFO:tensorflow:Restoring parameters from /tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/Trainer/model_run/6/serving_model_dir/model.ckpt-10000
INFO:tensorflow:Assets added to graph.
INFO:tensorflow:Assets written to: /tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/Trainer/model_run/6/eval_model_dir/temp-1606385814/assets
INFO:tensorflow:SavedModel written to: /tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/Trainer/model_run/6/eval_model_dir/temp-1606385814/saved_model.pb

INFO:absl:Exported eval_savedmodel to /tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/Trainer/model_run/6/eval_model_dir.
WARNING:absl:Support for estimator-based executor and model export will be deprecated soon. Please use export structure <ModelExportPath>/serving_model_dir/saved_model.pb"
INFO:absl:Serving model copied to: /tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/Trainer/model/6/serving_model_dir.
WARNING:absl:Support for estimator-based executor and model export will be deprecated soon. Please use export structure <ModelExportPath>/eval_model_dir/saved_model.pb"
INFO:absl:Eval model copied to: /tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/Trainer/model/6/eval_model_dir.
INFO:absl:Running publisher for Trainer
INFO:absl:MetadataStore with DB connection initialized

TensorBoardを使用してトレーニングを分析する

オプションで、TensorBoardをTrainerに接続して、モデルのトレーニング曲線を分析できます。

# Get the URI of the output artifact representing the training logs, which is a directory
model_run_dir = trainer.outputs['model_run'].get()[0].uri

%load_ext tensorboard
%tensorboard --logdir {model_run_dir}

評価者

Evaluatorコンポーネントは、評価セットのモデルパフォーマンスメトリックを計算します。 TensorFlowモデル分析ライブラリを使用します。 Evaluatorは、オプションで、新しくトレーニングされたモデルが以前のモデルよりも優れていることを検証することもできます。これは、モデルを毎日自動的にトレーニングおよび検証できる本番パイプライン設定で役立ちます。このノートブックでは、1つのモデルのみをトレーニングするため、 Evaluatorはモデルに「良好」のラベルを自動的に付けます。

Evaluator 、入力としてのデータがかかりますExampleGen 、から訓練を受けたモデルTrainer 、およびスライスの設定を。スライス構成を使用すると、機能値でメトリックをスライスできます(たとえば、午前8時と午後8時に開始するタクシー旅行でモデルがどのように機能するか)。以下のこの構成の例を参照してください。

eval_config = tfma.EvalConfig(
    model_specs=[
        # Using signature 'eval' implies the use of an EvalSavedModel. To use
        # a serving model remove the signature to defaults to 'serving_default'
        # and add a label_key.
        tfma.ModelSpec(signature_name='eval')
    ],
    metrics_specs=[
        tfma.MetricsSpec(
            # The metrics added here are in addition to those saved with the
            # model (assuming either a keras model or EvalSavedModel is used).
            # Any metrics added into the saved model (for example using
            # model.compile(..., metrics=[...]), etc) will be computed
            # automatically.
            metrics=[
                tfma.MetricConfig(class_name='ExampleCount')
            ],
            # To add validation thresholds for metrics saved with the model,
            # add them keyed by metric name to the thresholds map.
            thresholds = {
                'accuracy': tfma.MetricThreshold(
                    value_threshold=tfma.GenericValueThreshold(
                        lower_bound={'value': 0.5}),
                    change_threshold=tfma.GenericChangeThreshold(
                       direction=tfma.MetricDirection.HIGHER_IS_BETTER,
                       absolute={'value': -1e-10}))
            }
        )
    ],
    slicing_specs=[
        # An empty slice spec means the overall slice, i.e. the whole dataset.
        tfma.SlicingSpec(),
        # Data can be sliced along a feature column. In this case, data is
        # sliced along feature column trip_start_hour.
        tfma.SlicingSpec(feature_keys=['trip_start_hour'])
    ])

次に、この構成をEvaluator渡して実行します。

# Use TFMA to compute a evaluation statistics over features of a model and
# validate them against a baseline.

# The model resolver is only required if performing model validation in addition
# to evaluation. In this case we validate against the latest blessed model. If
# no model has been blessed before (as in this case) the evaluator will make our
# candidate the first blessed model.
model_resolver = ResolverNode(
      instance_name='latest_blessed_model_resolver',
      resolver_class=latest_blessed_model_resolver.LatestBlessedModelResolver,
      model=Channel(type=Model),
      model_blessing=Channel(type=ModelBlessing))
context.run(model_resolver)

evaluator = Evaluator(
    examples=example_gen.outputs['examples'],
    model=trainer.outputs['model'],
    #baseline_model=model_resolver.outputs['model'],
    # Change threshold will be ignored if there is no baseline (first run).
    eval_config=eval_config)
context.run(evaluator)
WARNING:absl:`instance_name` is deprecated, please set node id directly using`with_id()` or `.id` setter.
INFO:absl:Running driver for ResolverNode.latest_blessed_model_resolver
INFO:absl:MetadataStore with DB connection initialized
INFO:absl:Running publisher for ResolverNode.latest_blessed_model_resolver
INFO:absl:MetadataStore with DB connection initialized
INFO:absl:Running driver for Evaluator
INFO:absl:MetadataStore with DB connection initialized
INFO:absl:Running executor for Evaluator
WARNING:absl:"maybe_add_baseline" and "maybe_remove_baseline" are deprecated,
        please use "has_baseline" instead.
INFO:absl:Request was made to ignore the baseline ModelSpec and any change thresholds. This is likely because a baseline model was not provided: updated_config=
model_specs {
  signature_name: "eval"
}
slicing_specs {
}
slicing_specs {
  feature_keys: "trip_start_hour"
}
metrics_specs {
  metrics {
    class_name: "ExampleCount"
  }
  thresholds {
    key: "accuracy"
    value {
      value_threshold {
        lower_bound {
          value: 0.5
        }
      }
    }
  }
}

INFO:absl:Using /tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/Trainer/model/6/eval_model_dir as  model.
INFO:absl:The 'example_splits' parameter is not set, using 'eval' split.
INFO:absl:Evaluating model.

Warning:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow_model_analysis/eval_saved_model/load.py:169: load (from tensorflow.python.saved_model.loader_impl) is deprecated and will be removed in a future version.
Instructions for updating:
This function will only be available through the v1 compatibility library as tf.compat.v1.saved_model.loader.load or tf.compat.v1.saved_model.load. There will be a new function for importing SavedModels in Tensorflow 2.0.
INFO:tensorflow:Restoring parameters from /tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/Trainer/model/6/eval_model_dir/variables/variables
WARNING:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow_model_analysis/eval_saved_model/graph_ref.py:189: get_tensor_from_tensor_info (from tensorflow.python.saved_model.utils_impl) is deprecated and will be removed in a future version.
Instructions for updating:
This function will only be available through the v1 compatibility library as tf.compat.v1.saved_model.utils.get_tensor_from_tensor_info or tf.compat.v1.saved_model.get_tensor_from_tensor_info.

INFO:absl:Evaluation complete. Results written to /tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/Evaluator/evaluation/8.
INFO:absl:Checking validation results.
INFO:absl:Blessing result True written to /tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/Evaluator/blessing/8.
INFO:absl:Running publisher for Evaluator
INFO:absl:MetadataStore with DB connection initialized

次に、 Evaluatorの出力アーティファクトを調べてみましょう。

evaluator.outputs
{'evaluation': Channel(
    type_name: ModelEvaluation
    artifacts: [Artifact(artifact: id: 10
type_id: 20
uri: "/tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/Evaluator/evaluation/8"
custom_properties {
  key: "name"
  value {
    string_value: "evaluation"
  }
}
custom_properties {
  key: "producer_component"
  value {
    string_value: "Evaluator"
  }
}
custom_properties {
  key: "state"
  value {
    string_value: "published"
  }
}
state: LIVE
, artifact_type: id: 20
name: "ModelEvaluation"
)]
), 'blessing': Channel(
    type_name: ModelBlessing
    artifacts: [Artifact(artifact: id: 11
type_id: 21
uri: "/tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/Evaluator/blessing/8"
custom_properties {
  key: "blessed"
  value {
    int_value: 1
  }
}
custom_properties {
  key: "current_model"
  value {
    string_value: "/tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/Trainer/model/6"
  }
}
custom_properties {
  key: "current_model_id"
  value {
    int_value: 8
  }
}
custom_properties {
  key: "name"
  value {
    string_value: "blessing"
  }
}
custom_properties {
  key: "producer_component"
  value {
    string_value: "Evaluator"
  }
}
custom_properties {
  key: "state"
  value {
    string_value: "published"
  }
}
state: LIVE
, artifact_type: id: 21
name: "ModelBlessing"
)]
)}

evaluation出力を使用して、評価セット全体のグローバルメトリックのデフォルトの視覚化を表示できます。

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

スライスされた評価指標の視覚化を確認するには、TensorFlowモデル分析ライブラリを直接呼び出すことができます。

import tensorflow_model_analysis as tfma

# Get the TFMA output result path and load the result.
PATH_TO_RESULT = evaluator.outputs['evaluation'].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')
SlicingMetricsViewer(config={'weightedExamplesColumn': 'example_count'}, data=[{'slice': 'trip_start_hour:19',…

この視覚化は同じメトリックを示していますが、評価セット全体ではなく、 trip_start_hourすべての機能値で計算されています。

TensorFlow Model Analysisは、公平性インジケーターやモデルパフォーマンスの時系列のプロットなど、他の多くの視覚化をサポートしています。詳細については、チュートリアルを参照してください

構成にしきい値を追加したため、検証出力も利用できます。 blessing遺物の存在は、モデルが検証に合格したことを示しています。これが実行される最初の検証であるため、候補者は自動的に祝福されます。

blessing_uri = evaluator.outputs.blessing.get()[0].uri
!ls -l {blessing_uri}
total 0
-rw-rw-r-- 1 kbuilder kbuilder 0 Nov 26 10:17 BLESSED

検証結果レコードをロードして、成功を検証できるようになりました。

PATH_TO_RESULT = evaluator.outputs['evaluation'].get()[0].uri
print(tfma.load_validation_result(PATH_TO_RESULT))
validation_ok: true
validation_details {
  slicing_details {
    slicing_spec {
    }
    num_matching_slices: 25
  }
}


プッシャー

Pusherコンポーネントは通常、TFXパイプラインの最後にあります。モデルが検証に合格したかどうかをチェックし、合格した場合は、モデルを_serving_model_dirます。

pusher = Pusher(
    model=trainer.outputs['model'],
    model_blessing=evaluator.outputs['blessing'],
    push_destination=pusher_pb2.PushDestination(
        filesystem=pusher_pb2.PushDestination.Filesystem(
            base_directory=_serving_model_dir)))
context.run(pusher)
INFO:absl:Running driver for Pusher
INFO:absl:MetadataStore with DB connection initialized
INFO:absl:Running executor for Pusher
INFO:absl:Model version: 1606385828
INFO:absl:Model written to serving path /tmp/tmpdyqisj4r/serving_model/taxi_simple/1606385828.
INFO:absl:Model pushed to /tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/Pusher/pushed_model/9.
INFO:absl:Running publisher for Pusher
INFO:absl:MetadataStore with DB connection initialized

Pusherの出力アーティファクトを調べてみましょう。

pusher.outputs
{'pushed_model': Channel(
    type_name: PushedModel
    artifacts: [Artifact(artifact: id: 12
type_id: 23
uri: "/tmp/tfx-interactive-2020-11-26T10_13_22.805724-fe5em05p/Pusher/pushed_model/9"
custom_properties {
  key: "name"
  value {
    string_value: "pushed_model"
  }
}
custom_properties {
  key: "producer_component"
  value {
    string_value: "Pusher"
  }
}
custom_properties {
  key: "pushed"
  value {
    int_value: 1
  }
}
custom_properties {
  key: "pushed_destination"
  value {
    string_value: "/tmp/tmpdyqisj4r/serving_model/taxi_simple/1606385828"
  }
}
custom_properties {
  key: "pushed_version"
  value {
    string_value: "1606385828"
  }
}
custom_properties {
  key: "state"
  value {
    string_value: "published"
  }
}
state: LIVE
, artifact_type: id: 23
name: "PushedModel"
)]
)}

特に、プッシャーはモデルをSavedModel形式でエクスポートします。これは次のようになります。

push_uri = pusher.outputs.model_push.get()[0].uri
model = tf.saved_model.load(push_uri)

for item in model.signatures.items():
  pp.pprint(item)
('regression', <ConcreteFunction pruned(inputs) at 0x7F46B81E1630>)
('classification', <ConcreteFunction pruned(inputs) at 0x7F46B8375828>)
('predict', <ConcreteFunction pruned(examples) at 0x7F46D1325F28>)
('serving_default', <ConcreteFunction pruned(inputs) at 0x7F46A0410F28>)

組み込みのTFXコンポーネントのツアーが終了しました。