介绍TensorFlow决策森林

658 阅读7分钟

发布者:Mathieu Guillame-Bert, Sebastian Bruch,Josh Gordon, Jan Pfeifer

我们很高兴能开放TensorFlow决策森林(TF-DF)的源代码。TF-DF是一个生产就绪的最先进的算法集合,用于训练、服务和解释决策森林模型(包括随机森林和梯度提升的树)。你现在可以将这些模型用于分类、回归和排名任务--具有TensorFlow和Keras的灵活性和可组合性。

GIF showing Random Forest decision model
随机森林是一种流行的决策森林模型的类型。在这里,你可以看到一个树的森林通过对结果的投票对一个例子进行分类。

关于决策森林

决策森林是机器学习算法的一个系列,其质量和速度可以与神经网络相媲美(通常对神经网络有利),特别是当你在处理表格数据时。它们由许多决策树构建而成,这使得它们易于使用和理解--而且你可以利用今天已经存在的大量可解释性工具和技术。

TF-DF为TensorFlow用户带来了这一类的模型以及一套量身定做的工具。

  • 初学者会发现开发和解释决策森林模型比较容易。不需要明确列出或预处理输入特征(因为决策森林可以自然地处理数字和分类属性),不需要指定架构(例如,像在神经网络中那样尝试不同的层的组合),也不需要担心模型的分歧。一旦你的模型被训练好了,你可以直接绘制它,或者用容易解释的统计数据来分析它。

  • 高级用户将受益于具有非常快的推理时间的模型(在许多情况下,每个例子都是亚微秒)。而且,这个库为模型实验和研究提供了大量的可组合性。特别是,它很容易结合神经网络和决策森林。

如果你已经在TensorFlow之外使用决策森林,这里有一点TF-DF提供的东西。

  • 它提供了一系列最先进的决策森林训练和服务算法,如随机森林、梯度增强树、CART、(Lambda)MART、DART、额外树、贪婪的全局增长、倾斜树、单侧采样、分类集学习、随机分类学习、袋外评估和特征重要性以及结构特征重要性。

  • 这个库可以作为通往丰富的TensorFlow生态系统的桥梁,使你更容易将基于树的模型与各种TensorFlow工具和平台(如TFX)集成。

  • 而对于刚接触神经网络的用户来说,你可以用决策森林作为一种简单的方式来开始使用TensorFlow,并从那里继续探索神经网络。

代码示例

一个好的例子胜过千言万语。所以在这篇博文中,我们将展示用TensorFlow决策森林训练一个模型是多么容易。更多的例子可以在TF-DF网站GitHub页面上找到。你也可以观看我们在Google I/O 2021的演讲

训练一个模型

让我们从一个最小的例子开始,我们在表格式帕尔默企鹅数据集上训练一个随机森林模型。我们的目标是根据动物的特征来预测动物的种类。该数据集包含数字和分类特征,以csv文件的形式存储。

Three examples from the Palmer's Penguins dataset.
Palmer's Penguins数据集中的三个例子。

我们来训练一个模型。

# Install TensorFlow Decision Forests!pip install tensorflow_decision_forests# Load TensorFlow Decision Forestsimport tensorflow_decision_forests as tfdf# Load the training dataset using pandasimport pandastrain_df = pandas.read_csv("penguins_train.csv")# Convert the pandas dataframe into a TensorFlow datasettrain_ds = tfdf.keras.pd_dataframe_to_tf_dataset(train_df, label="species")# Train the modelmodel = tfdf.keras.RandomForestModel()model.fit(train_ds)

观察一下,在代码中我们没有任何地方提供输入特征或超参数。这意味着,TensorFlow决策森林将自动检测该数据集的输入特征,并对所有超参数使用默认值。

评估一个模型

现在,让我们评估一下我们模型的质量。

# Load the testing datasettest_df = pandas.read_csv("penguins_test.csv")# Convert it to a TensorFlow datasettest_ds = tfdf.keras.pd_dataframe_to_tf_dataset(test_df, label="species")# Evaluate the modelmodel.compile(metrics=["accuracy"])print(model.evaluate(test_ds))# >> 0.979311# Note: Cross-validation would be more suited on this small dataset.# See also the "Out-of-bag evaluation" below.# Export the model to a TensorFlow SavedModelmodel.save("project/my_first_model")

很简单,对吗?一个带有默认超参数的默认RandomForest模型为大多数问题提供了一个快速和良好的基线。一般来说,决策森林对于中小型问题会快速训练,与许多其他类型的模型相比,需要较少的超参数调整,并经常提供强大的结果。

解释一个模型

现在你已经看了训练好的模型的准确性,让我们来考虑它的可解释性。如果你希望理解和解释被建模的现象,调试一个模型,或者开始信任它的决定,可解释性是很重要的。如上所述,我们已经提供了一些工具来解释训练好的模型,首先是图谱。

tfdf.model_plotter.plot_model_in_colab(model, tree_idx=0)

tree structure

你可以直观地跟踪树状结构。在这棵树上,第一个决定是基于喙的长度。喙长于42.2毫米的企鹅可能是蓝色(巴布亚新几内亚)或绿色(钦斯特拉)物种,而喙短的企鹅可能是红色物种(阿德利)。

对于第一组,这棵树接着问到了脚蹼的长度。脚蹼长于206.5毫米的企鹅可能属于绿色物种(Chinstrap),而其余的则可能属于蓝色物种(Gentoo)。

模型统计是对图表的补充。统计的例子包括。

  • 每个特征的使用次数是多少?
  • 模型训练的速度有多快(以树的数量和时间计)?
  • 树结构中的节点是如何分布的(例如,大多数分支的长度是多少?)

这些以及更多此类询问的答案都包含在模型摘要中,可在模型检查器中查阅。

# Print all the available information about the modelmodel.summary()>> Input Features (7):>>   bill_depth_mm>>   bill_length_mm>>   body_mass_g>>   ...>> Variable Importance:>>   1.    "bill_length_mm" 653.000000 ################>>   ...>> Out-of-bag evaluation: accuracy:0.964602 logloss:0.102378>> Number of trees: 300>> Total number of nodes: 4170>>   ...# Get feature importance as a arraymodel.make_inspector().variable_importances()["MEAN_DECREASE_IN_ACCURACY"]>> [("flipper_length_mm", 0.149),>>      ("bill_length_mm", 0.096),>>      ("bill_depth_mm", 0.025),>>      ("body_mass_g", 0.018),>>      ("island", 0.012)]

在上面的例子中,模型是用默认的超参数值训练的。这是一个很好的初步解决方案,但是 "调整 "超参数往往可以进一步提高模型的质量。这可以像下面这样做。

# List all the other available learning algorithmstfdf.keras.get_all_models()>> [tensorflow_decision_forests.keras.RandomForestModel,>>  tensorflow_decision_forests.keras.GradientBoostedTreesModel,>>  tensorflow_decision_forests.keras.CartModel]# Display the hyper-parameters of the Gradient Boosted Trees model ? tfdf.keras.GradientBoostedTreesModel>> A GBT (Gradient Boosted [Decision] Tree) is a set of shallow decision trees trained sequentially. Each tree is trained to predict and then "correct" for the errors of the previously trained trees (more precisely each tree predicts the gradient of the loss relative to the model output)..   ...   Attributes:     num_trees: num_trees: Maximum number of decision trees. The effective number of trained trees can be smaller if early stopping is enabled. Default: 300.     max_depth: Maximum depth of the tree. `max_depth=1` means that all trees will be roots. Negative values are ignored. Default: 6.   ...# Create another model with specified hyper-parametersmodel = tfdf.keras.GradientBoostedTreesModel(    num_trees=500,    growing_strategy="BEST_FIRST_GLOBAL",    max_depth=8,    split_axis="SPARSE_OBLIQUE",    )# Evaluate the modelmodel.compile(metrics=["accuracy"])print(model.evaluate(test_ds))# >> 0.986851

接下来的步骤

我们希望你喜欢阅读这个关于TensorFlow决策森林的简短演示,并希望你能像我们开发它一样兴奋地使用它并为它作出贡献。

有了TensorFlow Decision Forests,你现在可以在TensorFlow中以最大的速度和质量来训练最先进的Decision Forests模型,并以最小的努力。如果你觉得冒险,你现在可以将决策森林和神经网络结合在一起,创建新型的混合模型。

如果你想了解更多关于TensorFlow决策森林库的信息,我们已经把一些资源放在一起,并推荐以下内容。

如果你有任何问题,请在discussion.tensorflow.org上使用 "TFDF "标签提问,我们会尽力帮助。再次感谢。