Copyright©2020Google Inc.
TensorFlow Extended(TFX)の機能エンジニアリングコンポーネント
このサンプルのcolabノートブックは、 TensorFlow Transform( tf.Transform
)を使用して、モデルのトレーニングとtf.Transform
推論の提供の両方にまったく同じコードを使用してデータを前処理する方法の非常に簡単な例を示しています。
TensorFlow Transformは、トレーニングデータセットのフルパスを必要とする機能の作成など、TensorFlowの入力データを前処理するためのライブラリです。たとえば、TensorFlow Transformを使用すると、次のことができます。
- 平均と標準偏差を使用して入力値を正規化します
- すべての入力値に対して語彙を生成することにより、文字列を整数に変換します
- 観測されたデータ分布に基づいて、フロートをバケットに割り当てることにより、フロートを整数に変換します
TensorFlowには、単一のサンプルまたはサンプルのバッチに対する操作のサポートが組み込まれています。 tf.Transform
はこれらの機能を拡張して、トレーニングデータセット全体のフルパスをサポートします。
tf.Transform
の出力は、トレーニングとサービングの両方に使用できるTensorFlowグラフとしてエクスポートされます。トレーニングとサービングの両方に同じグラフを使用すると、両方の段階で同じ変換が適用されるため、スキューを防ぐことができます。
アップグレードピップ
ローカルで実行しているときにシステムでPipをアップグレードしないようにするには、Colabで実行していることを確認してください。もちろん、ローカルシステムは個別にアップグレードできます。
try:
import colab
!pip install --upgrade pip
except:
pass
TensorFlowTransformをインストールします
pip install -q -U tensorflow_transform==0.24.1
ランタイムを再起動しましたか?
上記のセルを初めて実行するときにGoogleColabを使用している場合は、ランタイムを再起動する必要があります([ランタイム]> [ランタイムの再起動...])。これは、Colabがパッケージをロードする方法が原因です。
輸入
import pprint
import tempfile
import tensorflow as tf
import tensorflow_transform as tft
import tensorflow_transform.beam as tft_beam
from tensorflow_transform.tf_metadata import dataset_metadata
from tensorflow_transform.tf_metadata import schema_utils
データ:ダミーデータを作成します
簡単な例として、いくつかの簡単なダミーデータを作成します。
-
raw_data
は、前処理する最初の生データです。 -
raw_data_metadata
私たちの列の各種類告げるスキーマが含まraw_data
。この場合、それは非常に簡単です。
raw_data = [
{'x': 1, 'y': 1, 's': 'hello'},
{'x': 2, 'y': 2, 's': 'world'},
{'x': 3, 'y': 3, 's': 'hello'}
]
raw_data_metadata = dataset_metadata.DatasetMetadata(
schema_utils.schema_from_feature_spec({
'y': tf.io.FixedLenFeature([], tf.float32),
'x': tf.io.FixedLenFeature([], tf.float32),
's': tf.io.FixedLenFeature([], tf.string),
}))
変換:前処理関数を作成します
前処理機能は、tf.Transformの最も重要な概念です。前処理関数は、データセットの変換が実際に行われる場所です。テンソルの辞書を受け入れて返します。ここで、テンソルはTensor
またはSparseTensor
意味します。通常、前処理関数の中心を形成するAPI呼び出しには2つの主要なグループがあります。
- TensorFlow Ops:テンソルを受け入れて返す関数。通常はTensorFlowopsを意味します。これらは、生データを一度に1つの特徴ベクトルで変換されたデータに変換するグラフにTensorFlow操作を追加します。これらは、トレーニングとサービングの両方で、すべての例で実行されます。
- Tensorflow Transformアナライザー/マッパー: tf.Transformによって提供されるアナライザー/マッパーのいずれか。これらはテンソルも受け入れて返し、通常はTensorflow opsとBeam計算の組み合わせを含みますが、TensorFlow opsとは異なり、トレーニングデータセット全体のフルパスを必要とする分析中にのみBeamパイプラインで実行されます。ビーム計算はトレーニング中に1回だけ実行され、通常はトレーニングデータセット全体を完全に通過します。それらはテンソル定数を作成し、それがグラフに追加されます。たとえば、tft.minはトレーニングデータセットのテンソルの最小値を計算し、tft.scale_by_min_maxは最初にトレーニングデータセットのテンソルの最小値と最大値を計算してから、ユーザー指定の範囲[output_min、 output_max]。 tf.Transformは、そのようなアナライザー/マッパーの固定セットを提供しますが、これは将来のバージョンで拡張される予定です。
def preprocessing_fn(inputs):
"""Preprocess input columns into transformed columns."""
x = inputs['x']
y = inputs['y']
s = inputs['s']
x_centered = x - tft.mean(x)
y_normalized = tft.scale_to_0_1(y)
s_integerized = tft.compute_and_apply_vocabulary(s)
x_centered_times_y_normalized = (x_centered * y_normalized)
return {
'x_centered': x_centered,
'y_normalized': y_normalized,
's_integerized': s_integerized,
'x_centered_times_y_normalized': x_centered_times_y_normalized,
}
すべてを一緒に入れて
これで、データを変換する準備が整いました。ダイレクトランナーでApacheBeamを使用し、次の3つの入力を提供します。
-
raw_data
上記で作成した生の入力データ raw_data_metadata
生データのスキーマpreprocessing_fn
変換を行うために作成した関数
def main():
# Ignore the warnings
with tft_beam.Context(temp_dir=tempfile.mkdtemp()):
transformed_dataset, transform_fn = ( # pylint: disable=unused-variable
(raw_data, raw_data_metadata) | tft_beam.AnalyzeAndTransformDataset(
preprocessing_fn))
transformed_data, transformed_metadata = transformed_dataset # pylint: disable=unused-variable
print('\nRaw data:\n{}\n'.format(pprint.pformat(raw_data)))
print('Transformed data:\n{}'.format(pprint.pformat(transformed_data)))
if __name__ == '__main__':
main()
WARNING:tensorflow:Tensorflow version (2.3.2) 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.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. WARNING:tensorflow:Tensorflow version (2.3.2) 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:Tensorflow version (2.3.2) 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:You are passing instance dicts and DatasetMetadata to TFT which will not provide optimal performance. Consider following the TFT guide to upgrade to the TFXIO format (Apache Arrow RecordBatch). WARNING:tensorflow:You are passing instance dicts and DatasetMetadata to TFT which will not provide optimal performance. Consider following the TFT guide to upgrade to the TFXIO format (Apache Arrow RecordBatch). WARNING:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow_transform/tf_utils.py:218: Tensor.experimental_ref (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version. Instructions for updating: Use ref() instead. WARNING:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow_transform/tf_utils.py:218: Tensor.experimental_ref (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version. Instructions for updating: Use ref() instead. 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. 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:Assets added to graph. INFO:tensorflow:No assets to write. INFO:tensorflow:No assets to write. WARNING:tensorflow:Issue encountered when serializing tft_analyzer_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' WARNING:tensorflow:Issue encountered when serializing tft_analyzer_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' 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' 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/tmpj6tgub64/tftransform_tmp/9e2c0b621b1c4dedbf545511b1171544/saved_model.pb INFO:tensorflow:SavedModel written to: /tmp/tmpj6tgub64/tftransform_tmp/9e2c0b621b1c4dedbf545511b1171544/saved_model.pb INFO:tensorflow:Assets added to graph. INFO:tensorflow:Assets added to graph. INFO:tensorflow:No assets to write. INFO:tensorflow:No assets to write. WARNING:tensorflow:Issue encountered when serializing tft_analyzer_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' WARNING:tensorflow:Issue encountered when serializing tft_analyzer_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' 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' 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/tmpj6tgub64/tftransform_tmp/7e8a47e651934a98b60f04c2f38b3c88/saved_model.pb INFO:tensorflow:SavedModel written to: /tmp/tmpj6tgub64/tftransform_tmp/7e8a47e651934a98b60f04c2f38b3c88/saved_model.pb WARNING:tensorflow:Tensorflow version (2.3.2) 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:Tensorflow version (2.3.2) 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:You are passing instance dicts and DatasetMetadata to TFT which will not provide optimal performance. Consider following the TFT guide to upgrade to the TFXIO format (Apache Arrow RecordBatch). WARNING:tensorflow:You are passing instance dicts and DatasetMetadata to TFT which will not provide optimal performance. Consider following the TFT guide to upgrade to the TFXIO format (Apache Arrow RecordBatch). WARNING:apache_beam.options.pipeline_options:Discarding unparseable args: ['/home/kbuilder/.local/lib/python3.6/site-packages/ipykernel_launcher.py', '-f', '/tmp/tmp04j7jwel.json', '--HistoryManager.hist_file=:memory:'] 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: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 added to graph. INFO:tensorflow:Assets written to: /tmp/tmpj6tgub64/tftransform_tmp/c43b09cecac94afaa878f14ade8b6e90/assets INFO:tensorflow:Assets written to: /tmp/tmpj6tgub64/tftransform_tmp/c43b09cecac94afaa878f14ade8b6e90/assets INFO:tensorflow:SavedModel written to: /tmp/tmpj6tgub64/tftransform_tmp/c43b09cecac94afaa878f14ade8b6e90/saved_model.pb INFO:tensorflow:SavedModel written to: /tmp/tmpj6tgub64/tftransform_tmp/c43b09cecac94afaa878f14ade8b6e90/saved_model.pb WARNING:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef" value: "\n\013\n\tConst_3: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_3:0\022-vocab_compute_and_apply_vocabulary_vocabulary" 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 WARNING:tensorflow:Expected binary or unicode string, got type_url: "type.googleapis.com/tensorflow.AssetFileDef" value: "\n\013\n\tConst_3: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_3:0\022-vocab_compute_and_apply_vocabulary_vocabulary" 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 Raw data: [{'s': 'hello', 'x': 1, 'y': 1}, {'s': 'world', 'x': 2, 'y': 2}, {'s': 'hello', 'x': 3, 'y': 3}] Transformed data: [{'s_integerized': 0, 'x_centered': -1.0, 'x_centered_times_y_normalized': -0.0, 'y_normalized': 0.0}, {'s_integerized': 1, 'x_centered': 0.0, 'x_centered_times_y_normalized': 0.0, 'y_normalized': 0.5}, {'s_integerized': 0, 'x_centered': 1.0, 'x_centered_times_y_normalized': 1.0, 'y_normalized': 1.0}]
これは正しい答えですか?
以前は、これを行うためにtf.Transform
を使用していました。
x_centered = x - tft.mean(x)
y_normalized = tft.scale_to_0_1(y)
s_integerized = tft.compute_and_apply_vocabulary(s)
x_centered_times_y_normalized = (x_centered * y_normalized)
x_centered
[1, 2, 3]
入力すると、xの平均は2になり、xからそれを引いてx値を0に[-1.0, 0.0, 1.0]
ます。したがって、 [-1.0, 0.0, 1.0]
は正しいです。
y_normalized
y値を0から1の間でスケーリングしたかったのです。入力は[1, 2, 3]
だったので、 [0.0, 0.5, 1.0]
[1, 2, 3]
結果は正しいです。
s_integerized
文字列を語彙のインデックスにマッピングしたかったのですが、語彙には2つの単語(「hello」と「world」)しかありませんでした。だから、の入力して["hello", "world", "hello"]
の私達の結果[0, 1, 0]
正しいです。このデータでは「hello」が最も頻繁に発生するため、語彙の最初のエントリになります。
x_centered_times_y_normalized
乗算を使用してx_centered
とy_normalized
を交差さx_centered
により、新しい機能を作成したかったのです。これにより、元の値ではなく結果が乗算され、 [-0.0, 0.0, 1.0]
新しい結果が正しいことに注意してください。