接续 Day 15 的 tf.Tramsform 介绍,今日进行实作,先以TensorFlow Transform 预处理数据的入门范例 作为演示过程,官方 Colab 支援 , 您会发现 Apache Beam 的 pipeline 撰写方式融入在程序中。
try:
import colab
!pip install --upgrade pip
except:
pass
!pip install -q -U tensorflow_transform==0.24.1
pprint
输出比较漂亮。tempfile
生成暂存档案所需。tensorflow
已经是2.x版需引入。tensorflow_transform
简称 tft
。tensorflow_transform.beam
实现使用 Apache Beam 。tensorflow_transform.tf_metadata
为纪录数据所需要的 metadata 模组,引入 dataset_metadata
及 schema_utils
。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 = [
{'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),
}))
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,
}
现在我们已准备好转换我们的数据。我们将使用带有直接运行器的 Apache Beam,输入为:
raw_data
: 我们上面创建的原始输入数据。raw_data_metadata
: 原始数据的 Schema。preprocessing_fn
: 预处理的特徵工程函数。关於 Apache Beam 的特殊语法用到了会在 Linux 使用的 |
(pipe 运算子),可以理解为:
=
左边是最终结果 result。=
右边第一个是输入 pass_this,接续 |
是执行过程步骤。|
右边先命名
,再>>
执行。也可以省略命名直接 to_this_call。result = pass_this | 'name this step' >> to_this_call
result = apache_beam.Pipeline() | 'first step' >> do_this_first() | 'second step' >> do_this_last()
在此范例,创建了暂时资料夹,将raw_data, raw_data_metadata
作为 tft_beam.AnalyzeAndTransformDataset( preprocessing_fn)
的输入,执行结果输出存入 transformed_dataset, transform_fn
。
最後将 transformed_dataset
拆成 transformed_data
, transformed_metadata
,并列印原始资料以及经过前处理的资料对照。
def main():
# Ignore the warnings
with tft_beam.Context(temp_dir=tempfile.mkdtemp()):
transformed_dataset, transform_fn = (
(raw_data, raw_data_metadata) | tft_beam.AnalyzeAndTransformDataset(
preprocessing_fn))
transformed_data, transformed_metadata = transformed_dataset
print('\nRaw data:\n{}\n'.format(pprint.pformat(raw_data)))
print('Transformed data:\n{}'.format(pprint.pformat(transformed_data)))
if __name__ == '__main__':
main()
Pass Salesforce Omni Studios accreditation on the ...
HTML的注解是使用 <!-- --> 而CSS的注解是使用 /* */ 浏览器预设样式...
题号:59 标题:Spiral Matrix II 难度:Medium Given a positi...
大家好,我是毛毛。ヾ(´∀ ˋ)ノ 废话不多说开始今天的解题Day~ 46. Permutation...
知己知彼,百战百胜,在开始与客户洽谈之前,我们必须要尽可能地搜集客户的资料,才能为他们提供更好的规划...