梯度提升袋外估计

Beginner

This tutorial is from open-source community. Access the source code

简介

本实验将指导你使用 Python 中的 scikit-learn 库实现一个带有袋外(OOB)估计的梯度提升分类器。OOB 估计是交叉验证估计的一种替代方法,可以即时计算,无需重复进行模型拟合。本实验将涵盖以下步骤:

  1. 生成数据
  2. 使用 OOB 估计拟合分类器
  3. 使用交叉验证估计最佳迭代次数
  4. 计算测试数据的最佳迭代次数
  5. 绘制结果

虚拟机提示

虚拟机启动完成后,点击左上角切换到“笔记本”标签,以访问 Jupyter Notebook 进行练习。

有时,你可能需要等待几秒钟让 Jupyter Notebook 完成加载。由于 Jupyter Notebook 的限制,操作验证无法自动化。

如果你在学习过程中遇到问题,请随时向 Labby 提问。课程结束后提供反馈,我们将立即为你解决问题。

生成数据

第一步是生成一些示例数据,用于训练和测试我们的模型。我们将使用 sklearn.datasets 模块中的 make_classification 函数来生成一个具有 3 个信息特征的随机二分类问题。

import numpy as np
from sklearn.datasets import make_classification

X, y = make_classification(n_samples=1000, n_features=3, n_informative=3,
                           n_redundant=0, n_classes=2, random_state=1)

使用袋外估计拟合分类器

接下来,我们将使用 sklearn.ensemble 模块中的 GradientBoostingClassifier 类创建一个带有袋外估计的梯度提升分类器。我们将估计器的数量设置为 100,学习率设置为 0.1。

from sklearn.ensemble import GradientBoostingClassifier

params = {
    "n_estimators": 100,
    "learning_rate": 0.1,
    "subsample": 1.0,
    "max_depth": 3,
    "min_samples_leaf": 1,
    "random_state": 1,
    "oob_score": True
}

clf = GradientBoostingClassifier(**params)
clf.fit(X, y)

使用交叉验证估计最佳迭代次数

我们可以使用交叉验证来估计最佳迭代次数。我们将使用五折交叉验证,并计算每个迭代次数的负对数损失。

from sklearn.model_selection import cross_val_score

cv_scores = []
for i in range(1, params['n_estimators'] + 1):
    clf.set_params(n_estimators=i)
    scores = -1 * cross_val_score(clf, X, y, cv=5, scoring='neg_log_loss')
    cv_scores.append(scores.mean())

计算测试数据的最佳迭代次数

我们还可以计算测试数据的最佳迭代次数。我们将计算测试数据上每个迭代次数的负对数损失。

from sklearn.metrics import log_loss
import matplotlib.pyplot as plt

test_scores = []
for i, y_pred in enumerate(clf.staged_predict_proba(X)):
    score = log_loss(y, y_pred)
    test_scores.append(score)

best_n_estimators = np.argmin(test_scores) + 1

绘制结果

最后,我们可以绘制结果,以直观展示模型在不同迭代次数下的性能。我们将在 y 轴上绘制负对数损失,在 x 轴上绘制迭代次数。

plt.figure(figsize=(10, 5))
plt.plot(range(1, params['n_estimators'] + 1), cv_scores, label='CV')
plt.plot(range(1, params['n_estimators'] + 1), test_scores, label='Test')
plt.axvline(x=best_n_estimators, color='red', linestyle='--')
plt.xlabel('Number of iterations')
plt.ylabel('Negative log-loss')
plt.legend()
plt.show()

总结

在本实验中,我们学习了如何实现一个带有袋外估计的梯度提升分类器,并使用交叉验证来估计最佳迭代次数。我们还计算了测试数据的最佳迭代次数,并绘制结果以直观展示模型在不同迭代次数下的性能。