如何将 Tensorflow 和 Estimator 与 Boosted 树一起使用来训练和评估模型?

tensorflowserver side programmingprogramming更新于 2025/5/20 2:22:17

借助‘BoostedTreesClassifier’,可以将 Tensorflow 和 Estimator 与 Boosted 树一起使用来训练和评估模型。此估算器与‘train’方法和‘evaluate’一起使用方法分别训练和评估数据集。

阅读更多: 什么是 TensorFlow,以及 Keras 如何与 TensorFlow 配合使用来创建神经网络?

我们将使用 Keras Sequential API,它有助于构建用于处理普通层堆栈的顺序模型,其中每个层都有一个输入张量和一个输出张量。

包含至少一个层的神经网络称为卷积层。我们可以使用卷积神经网络构建学习模型。

我们使用 Google Colaboratory 运行以下代码。Google Colab 或 Colaboratory 有助于在浏览器上运行 Python 代码,无需配置,可以免费访问 GPU(图形处理单元)。Colaboratory 建立在 Jupyter Notebook 之上。

我们将了解如何使用决策树和 tf.estimator API 训练梯度提升模型。

让我们了解如何使用估算器。估算器是 TensorFlow 对完整模型的高级表示。它专为轻松扩展和异步训练而设计。

我们将使用 tf.estimator API 训练逻辑回归模型。该模型用作其他算法的基线。我们使用泰坦尼克号数据集,目标是预测乘客的生存情况,给定性别、年龄、等级等特征。

估算器使用特征列来描述模型如何解释原始输入特征。估算器需要一个数字输入向量,特征列将有助于描述模型应如何转换数据集中的每个特征。选择和使用正确的特征列集对于学习有效的模型至关重要。特征列可以是原始特征字典中的原始输入之一,也可以是使用在一个或多个基础列上定义的转换创建的新列。

增强树模型被认为是回归和分类最流行和最有效的机器学习方法。它是一种集成技术,结合了来自许多(10 个、100 个或 1000 个)树模型的预测。

BoostedTreesRegressor 和分类支持 BoostedTreesClassifier。目标是预测一个类,即生存或不生存。

示例

print("Using boosted trees")
print("Data fits into memory, hence entire dataset per layer is used as a single batch")
print("This would be quick")
n_batches = 1
est = tf.estimator.BoostedTreesClassifier(feature_columns,
n_batches_per_layer=n_batches)
print("The model stops training once the number of trees specified is built")
est.train(train_input_fn, max_steps=100)
print("The model is evaluated")
result = est.evaluate(eval_input_fn)
clear_output()
print(pd.Series(result))

输出

accuracy              0.833333
accuracy_baseline     0.625000
auc                   0.875237
auc_precision_recall  0.859974
average_loss          0.405130
label/mean            0.375000
loss                  0.405130
precision             0.795699
prediction/mean       0.383989
recall                0.747475
global_step         100.000000
dtype: float64

解释

  • Boosted Trees 模型已训练完毕。
  • 目标是预测一个类别,该类别可能存活或不存活。
  • 为此,使用 BoostedTreesClassifier。

相关文章