Day 16 : 特徵工程 tf.Tramsform 实作

接续 Day 15 的 tf.Tramsform 介绍,今日进行实作,先以TensorFlow Transform 预处理数据的入门范例 作为演示过程,官方 Colab 支援 , 您会发现 Apache Beam 的 pipeline 撰写方式融入在程序中。

TFT 特徵工程简易入门

1. 建立环境

  • 因为 Colab 的套件版本问题,pip 需更新并安装 tensorflow_transform 套件,安装需要时间,并且应该要重新启动(执行阶段>重新启动执行阶段)。
    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_metadataschema_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
    

2. 创建资料及中继资料 matadata

  • 在此范例的模拟假资料,您就当是 tft 的 Hello world 。
  • 用於生产的机械学习基於任务情境及後续应用,接收到的资料很有可能是采用 JSON 形式,透过 Request 取得的 RESTFUL 资料。
    raw_data = [
          {'x': 1, 'y': 1, 's': 'hello'},
          {'x': 2, 'y': 2, 's': 'world'},
          {'x': 3, 'y': 3, 's': 'hello'}
      ]
    
  • 定义资料特徵的 Schema 。
    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),
        }))
    

3. 撰写预处理函数 preprocessing_fn()

  • tf.Tramsform 已经实作许多特徵工程的函数,您可以参考 TFX API 文件
    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,
        }
    

4. 组合流程

  • 现在我们已准备好转换我们的数据。我们将使用带有直接运行器的 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()
    

小结

  • 以上为TensorFlow Transform 预处理数据的入门范例演示过程,高级版的已经包含後续训练与评估的流程,您可以迳行参考执行。
  • 笔者理解 tf.Transform 花了不少时间,这篇简要整理您所需之道的内容,仍希望能帮助到您。

参考


<<:  Day 01 - 前言

>>:  [13th][Day6] func

Exactly how To Come To Be A Salesforce Omni Programmer Qualification?

Pass Salesforce Omni Studios accreditation on the ...

【後转前要多久】# Day08 CSS - CSS Reset

HTML的注解是使用 <!-- --> 而CSS的注解是使用 /* */ 浏览器预设样式...

找LeetCode上简单的题目来撑过30天啦(DAY29)

题号:59 标题:Spiral Matrix II 难度:Medium Given a positi...

Day 25 - Permutations

大家好,我是毛毛。ヾ(´∀ ˋ)ノ 废话不多说开始今天的解题Day~ 46. Permutation...

试着掌握潜在客户需求

知己知彼,百战百胜,在开始与客户洽谈之前,我们必须要尽可能地搜集客户的资料,才能为他们提供更好的规划...