如何从提升树 Estimator 迁移到 TensorFlow 决策森林

2022 年 4 月 18 日 TensorFlow


发布人:TensorFlow 团队的 Mathieu Guillame-Bert 和 Josh Gordon


随机森林梯度提升树这类的决策森林模型通常是处理表格数据最有效的可用工具。与神经网络相比,决策森林具有更多优势,如配置过程更轻松、训练速度更快等。使用树可大幅减少准备数据集所需的代码量,因为这些树本身就可以处理数字、分类和缺失的特征。此外,这些树通常还可提供开箱即用的良好结果,并具有可解释的属性。

  • 随机森林

    https://developers.google.cn/machine-learning/glossary#random-forest

  • 梯度提升树

    https://developers.google.cn/machine-learning/glossary#gradient-boosted-decision-trees-gbt


尽管我们通常将 TensorFlow 视为训练神经网络的内容库,但 Google 的一个常见用例是使用 TensorFlow 创建决策森林。


对数据开展分类的决策树动画


如果您曾使用 2019 年推出tf.estimator.BoostedTrees 创建基于树的模型,您可参考本文所提供的指南进行迁移。虽然 Estimator API 基本可以应对在生产环境中使用模型的复杂性,包括分布式训练和序列化,但是我们不建议您将其用于新代码。

  • tf.estimator.BoostedTrees

    https://tensorflow.google.cn/api_docs/python/tf/estimator/BoostedTreesClassifier


如果您要开始一个新项目,我们建议您使用 TensorFlow 决策森林 (TF-DF)。该内容库可为训练、服务和解读决策森林模型提供最先进的算法,相较于先前的方法更具优势,特别是在质量、速度和易用性方面表现尤为出色。


首先,让我们来比较一下使用 Estimator API 和 TF-DF 创建提升树模型的等效示例。


以下是使用 tf.estimator.BoostedTrees 训练梯度提升树模型的旧方法(不再推荐使用)


import tensorflow as tf

# Dataset generators
def make_dataset_fn(dataset_path):
def make_dataset():
data = ... # read dataset
return tf.data.Dataset.from_tensor_slices(...data...).repeat(10).batch(64)
return make_dataset

# List the possible values for the feature "f_2".
f_2_dictionary = ["NA", "red", "blue", "green"]

# The feature columns define the input features of the model.
feature_columns = [
tf.feature_column.numeric_column("f_1"),
tf.feature_column.indicator_column(
tf.feature_column.categorical_column_with_vocabulary_list("f_2",
f_2_dictionary,
# A special value "missing" is used to represent missing values.
default_value=0)
),
]

# Configure the estimator
estimator = boosted_trees.BoostedTreesClassifier(
n_trees=1000,
feature_columns=feature_columns,
n_classes=3,
# Rule of thumb proposed in the BoostedTreesClassifier documentation.
n_batches_per_layer=max(2, int(len(train_df) / 2 / FLAGS.batch_size)),
)

# Stop the training is the validation loss stop decreasing.
early_stopping_hook = early_stopping.stop_if_no_decrease_hook(
estimator,
metric_name="loss",
max_steps_without_decrease=100,
min_steps=50)

tf.estimator.train_and_evaluate(
estimator,
train_spec=tf.estimator.TrainSpec(
make_dataset_fn(train_path),
hooks=[
# Early stopping needs a CheckpointSaverHook.
tf.train.CheckpointSaverHook(
checkpoint_dir=input_config.raw.temp_dir, save_steps=500),
early_stopping_hook,
]),
eval_spec=tf.estimator.EvalSpec(make_dataset_fn(valid_path)))


使用 TensorFlow 决策森林训练相同的模型


import tensorflow_decision_forests as tfdf

# Load the datasets
# This code is similar to the estimator.
def make_dataset(dataset_path):
data = ... # read dataset
return tf.data.Dataset.from_tensor_slices(...data...).batch(64)

train_dataset = make_dataset(train_path)
valid_dataset = make_dataset(valid_path)

# List the input features of the model.
features = [
tfdf.keras.FeatureUsage("f_1", keras.FeatureSemantic.NUMERICAL),
tfdf.keras.FeatureUsage("f_2", keras.FeatureSemantic.CATEGORICAL),
]

model = tfdf.keras.GradientBoostedTreesModel(
task = tfdf.keras.Task.CLASSIFICATION,
num_trees=1000,
features=features,
exclude_non_specified_features=True)

model.fit(train_dataset, valid_dataset)

# Export the model to a SavedModel.
model.save("project/model")


附注


  • 虽然在此示例中没有明确说明,但 TensorFlow 决策森林可自动启用和配置早停。

  • 自动构建和优化“f_2”特征字典(例如,将稀有值合并到一个未登录词项目中)。

  • 可从数据集中自动确定类别数(本例中为 3 个)。

  • 批次大小(本例中为 64)对模型训练没有影响。以较大值为宜,因为这可以增加读取数据集的效率。


TF-DF 的亮点就在于简单易用,我们还可进一步简化和完善上述示例,如下所示。


如何训练 TensorFlow 决策森林(推荐解决方案)


import tensorflow_decision_forests as tfdf
import pandas as pd

# Pandas dataset can be used easily with pd_dataframe_to_tf_dataset.
train_df = pd.read_csv("project/train.csv")

# Convert the Pandas dataframe into a TensorFlow dataset.
train_ds = tfdf.keras.pd_dataframe_to_tf_dataset(train_df, label="my_label")

model = tfdf.keras.GradientBoostedTreeModel(num_trees=1000)
model.fit(train_dataset)


附注


  • 我们未指定特征的语义(例如数字或分类)。在这种情况下,系统将自动推断语义。

  • 我们也没有列出要使用的输入特征。在这种情况下,系统将使用所有列(标签除外)。可在训练日志中查看输入特征的列表和语义,或通过模型检查器 API 查看。

  • 我们没有指定任何验证数据集。每个算法都可以从训练样本中提取一个验证数据集作为算法的最佳选择。例如,默认情况下,如果未提供验证数据集,则 GradientBoostedTreeModel 将使用 10% 的训练数据进行验证。


下面我们将介绍 Estimator API 和 TF-DF 的一些区别。


Estimator API 和 TF-DF 的区别


算法类型


TF-DF 是决策森林算法的集合,包括(但不限于)Estimator API 提供的梯度提升树。请注意,TF-DF 还支持随机森林(非常适用于干扰数据集)和 CART 实现(非常适用于解读模型)。

  • 随机森林

    https://tensorflow.google.cn/decision_forests/api_docs/python/tfdf/keras/RandomForestModel

  • CART

    https://g3doc.corp.google.com/third_party/tensorflow/google/g3doc/use_tensorflow/migration_decision_forests.md?cl=432890187#:~:text=nosy%20datasets)%20and%20a-,CART,-implementation%20(great%20for


此外,对于每个算法,TF-DF 都包含许多在文献资料中发现并经过实验验证的变体 [1, 2, 3]。

  • 1

    https://arxiv.org/abs/2009.09991

  • 2

    https://arxiv.org/abs/1603.02754

  • 3

    https://proceedings.neurips.cc/paper/2017/file/6449f44a102fde848669bdd9eb6b76fa-Paper.pdf


精确与近似分块的对比


TF1 GBT Estimator 是一种近似的树学习算法。非正式情况下,Estimator 通过仅考虑样本的随机子集和每个步骤条件的随机子集来构建

  • 构建

    http://ecmlpkdd2017.ijs.si/papers/paperID705.pdf


默认情况下,TF-DF 是一种精确的树训练算法。非正式情况下,TF-DF 会考虑所有训练样本和每个步骤的所有可能分块。这是一种更常见且通常表现更佳的解决方案。


虽然对于较大的数据集(具有百亿数量级以上的“样本和特征”数组)而言,有时 Estimator 的速度更快,但其近似值通常不太准确(因为需要种植更多树才能达到相同的质量)。而对于小型数据集(所含的“样本和特征”数组数目不足一亿)而言,使用 Estimator 实现近似训练形式的速度甚至可能比精确训练更慢。


TF-DF 还支持不同类型的“近似”树训练。我们建议您使用精确训练法,并选择使用大型数据集测试近似训练。


推理


Estimator 使用自上而下的树路由算法运行模型推理。TF-DF 使用 QuickScorer 算法的扩展程序。

  • 自上而下的树路由算法

    https://developers.google.cn/machine-learning/decision-forests/decision-trees

  • QuickScorer

    http://ecmlpkdd2017.ijs.si/papers/paperID718.pdf


虽然两种算法返回的结果完全相同,但自上而下的算法效率较低,因为这种算法的计算量会超出分支预测并导致缓存未命中。对于同一模型,TF-DF 的推理速度通常可提升 10 倍。


TF-DF 可为延迟关键应用程序提供 C++ API。其推理时间约为每核心每样本 1 微秒。与 TF SavedModel 推理相比,这通常可将速度提升 50 至 1000 倍(对小型批次的效果更佳)。

  • C++ API

    https://g3doc.corp.google.com/third_party/tensorflow/google/g3doc/use_tensorflow/migration_decision_forests.md?cl=432890187#:~:text=TF%2DDF%20offers%20a-,C%2B%2B%20API,-.%20It%20provides%20often


多头模型


Estimator 支持多头模型(即输出多种预测的模型)。目前,TF-DF 无法直接支持多头模型,但是借助 Keras Functional API,TF-DF 可以将多个并行训练的 TF-DF 模型组成一个多头模型。


了解详情


您可以访问此网址,详细了解 TensorFlow 决策森林。

  • 网址

    https://tensorflow.google.cn/decision_forests/


如果您是首次接触该内容库,我们建议您从初学者示例开始。经验丰富的 TensorFlow 用户可以访问此指南,详细了解有关在 TensorFlow 中使用决策森林和神经网络的区别要点,包括如何配置训练流水线和关于数据集 I/O 的提示。

  • 初学者示例

    https://tensorflow.google.cn/decision_forests/tutorials/beginner_colab

  • 指南

    https://github.com/tensorflow/decision-forests/blob/main/documentation/migration.md


您还可以仔细阅读从 Estimator 迁移到 Keras API,了解如何从 Estimator 迁移到 Keras。

  • 从 Estimator 迁移到 Keras API

    https://tensorflow.google.cn/guide/migrate/migrating_estimator


推荐阅读


TensorFlow 决策森林来啦!


点击“阅读原文”访问 TensorFlow 官网



不要忘记“一键三连”哦~

分享

点赞

在看

登录查看更多
0

相关内容

专知会员服务
38+阅读 · 2020年9月6日
TensorFlow Lite指南实战《TensorFlow Lite A primer》,附48页PPT
专知会员服务
68+阅读 · 2020年1月17日
KGCN:使用TensorFlow进行知识图谱的机器学习
专知会员服务
80+阅读 · 2020年1月13日
Keras 预处理层了解一下
TensorFlow
2+阅读 · 2022年1月4日
TensorFlow Lite 设备端训练
TensorFlow
4+阅读 · 2021年12月20日
TensorFlow 模型优化工具包:协作优化 API
TensorFlow
1+阅读 · 2021年11月29日
TensorFlow 决策森林来啦!
TensorFlow
0+阅读 · 2021年6月1日
一起看 I/O | TensorFlow 的最新资讯,一文全掌握
TensorFlow
0+阅读 · 2021年5月25日
社区分享 | Spark 玩转 TensorFlow 2.0
TensorFlow
15+阅读 · 2020年3月18日
如何用TF Serving部署TensorFlow模型
AI研习社
26+阅读 · 2019年3月27日
TF Boys必看!一文搞懂TensorFlow 2.0新架构!
引力空间站
18+阅读 · 2019年1月16日
国家自然科学基金
0+阅读 · 2015年12月31日
国家自然科学基金
4+阅读 · 2014年12月31日
国家自然科学基金
0+阅读 · 2013年12月31日
国家自然科学基金
0+阅读 · 2013年12月31日
国家自然科学基金
1+阅读 · 2012年12月31日
国家自然科学基金
0+阅读 · 2012年12月31日
国家自然科学基金
0+阅读 · 2009年12月31日
国家自然科学基金
0+阅读 · 2009年12月31日
国家自然科学基金
0+阅读 · 2008年12月31日
国家自然科学基金
12+阅读 · 2008年12月31日
Arxiv
0+阅读 · 2022年6月7日
Arxiv
0+阅读 · 2022年6月7日
Interest-aware Message-Passing GCN for Recommendation
Arxiv
11+阅读 · 2021年2月19日
Arxiv
10+阅读 · 2018年4月19日
VIP会员
相关资讯
Keras 预处理层了解一下
TensorFlow
2+阅读 · 2022年1月4日
TensorFlow Lite 设备端训练
TensorFlow
4+阅读 · 2021年12月20日
TensorFlow 模型优化工具包:协作优化 API
TensorFlow
1+阅读 · 2021年11月29日
TensorFlow 决策森林来啦!
TensorFlow
0+阅读 · 2021年6月1日
一起看 I/O | TensorFlow 的最新资讯,一文全掌握
TensorFlow
0+阅读 · 2021年5月25日
社区分享 | Spark 玩转 TensorFlow 2.0
TensorFlow
15+阅读 · 2020年3月18日
如何用TF Serving部署TensorFlow模型
AI研习社
26+阅读 · 2019年3月27日
TF Boys必看!一文搞懂TensorFlow 2.0新架构!
引力空间站
18+阅读 · 2019年1月16日
相关基金
国家自然科学基金
0+阅读 · 2015年12月31日
国家自然科学基金
4+阅读 · 2014年12月31日
国家自然科学基金
0+阅读 · 2013年12月31日
国家自然科学基金
0+阅读 · 2013年12月31日
国家自然科学基金
1+阅读 · 2012年12月31日
国家自然科学基金
0+阅读 · 2012年12月31日
国家自然科学基金
0+阅读 · 2009年12月31日
国家自然科学基金
0+阅读 · 2009年12月31日
国家自然科学基金
0+阅读 · 2008年12月31日
国家自然科学基金
12+阅读 · 2008年12月31日
Top
微信扫码咨询专知VIP会员