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

如何从提升树 Estimator 迁移到 TensorFlow 决策森林
www.zeeklog.com  - 如何从提升树 Estimator 迁移到 TensorFlow 决策森林
www.zeeklog.com  - 如何从提升树 Estimator 迁移到 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 创建决策森林。

www.zeeklog.com  - 如何从提升树 Estimator 迁移到 TensorFlow 决策森林

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

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

tf.estimator.BoostedTrees

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

如果您要开始一个新项目,我们建议您使用  (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

www.zeeklog.com  - 如何从提升树 Estimator 迁移到 TensorFlow 决策森林
www.zeeklog.com  - 如何从提升树 Estimator 迁移到 TensorFlow 决策森林
www.zeeklog.com  - 如何从提升树 Estimator 迁移到 TensorFlow 决策森林

Read more

Java——Stream流式编程

Java——Stream流式编程

Java——Stream流式编程 * * * 本文记录一下Java8新特性Stream流式编程的使用。 一、什么是Stream流式操作 Stream流式操作,就是学习java.util.stream包下的API,Stream不同于java的输入输出流,是实现对集合(Collection)的复杂操作,例如查找、替换、过滤和映射数据等,集合是一种静态的数据结构,存储在内存中,而Stream是用于计算的,通过CPU实现计算,因此可以认为Stream就是处理集合数据的各种算法流程。 二、Stream流式操作流程 Stream流式操作主要有 3 个步骤: * 创建Stream对象:通过一些数据源创建流对象 * 中间操作:对数据源的数据进行处理(过滤、排序等) * 终止操作:一旦执行终止操作, 就执行中间的链式操作,并产生结果。 三、3个步骤详细解析 1. 创建Stream对象 创建stream流对象有以下几种方式: * 通过集合创建 Stream * 通过数组创建 Stream * 通过 Stream 的 of()方法

By Ne0inhk
Java中的序列化和反序列化详解!!!

Java中的序列化和反序列化详解!!!

Java中的序列化和反序列化详解 * * Java中的序列化和反序列化是用于在对象和字节流之间进行转换的机制,可以将对象转换为字节流进行存储或传输,然后再将字节流转换回对象。下面将结合代码详细介绍Java中的序列化和反序列化。 1. 序列化 序列化是将对象转换为字节流的过程,可以通过实现 Serializable 接口来实现对象的序列化。 代码如下: import java.io.*; // 定义一个可序列化的Person类 需要实现Serializable接口 class Person implements Serializable { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String toString() { return "Person{name='" + name +

By Ne0inhk
java8 Optional 使用方法详解

java8 Optional 使用方法详解

java8 Optional 使用方法详解 * * 本文总结一下java8 Optional 使用方法详解。 一、Optional介绍 Optional类是 Java 8 中引入的一个用于解决空指针异常的类,它可以表示一个值存在或不存在。 二、Optional类的使用 1. 创建Optional类 创建Optional类有两种方式: * 使用 Optional.of() 方法创建一个包含非空值的 Optional 对象。 * 使用 Optional.empty() 方法创建一个空的 Optional 对象。 Optional<String> optionalWithValue = Optional.of("Hello"); Optional<String> optionalEmpty = Optional.empty(); 2. Optional类的常用方法 * isPresent(

By Ne0inhk
Java——函数式接口

Java——函数式接口

Java——函数式接口 * * 本文记录一下java 函数式接口。   函数式接口是Java 8中引入的一个新特性,它是只包含一个抽象方法的接口。函数式接口可以使用Lambda表达式(关于lambda表达式可以看我的另一篇博文)来实现,从而实现函数式编程的特性。在函数式接口中,也可以定义默认方法和静态方法,但只能有一个抽象方法。 下面使用代码示例说明函数是接口的使用: 1. 定义一个函数式接口 @FunctionalInterface interface MyFunction { int calculate(int a, int b); // 抽象方法 default void printMessage() { //默认方法 System.out.println("This is a default method."); } static void printStaticMessage() { //静态方法 System.out.println("This

By Ne0inhk