注意
跳转至页面底部 下载完整示例代码,或通过 JupyterLite 或 Binder 在浏览器中运行此示例。
基于 AdaBoost 的决策树回归#
本示例展示了在包含少量高斯噪声的一维正弦数据集上,使用 AdaBoost.R2 [1] 算法对决策树进行增强。我们将 299 次增强(共 300 棵决策树)的结果与单个决策树回归器进行了对比。随着增强次数的增加,回归器能够拟合出更多的细节。
请参阅 直方图梯度提升树的特性,了解使用更高效的回归模型(如 HistGradientBoostingRegressor)的优势。
准备数据#
首先,我们准备一组具有正弦关系并包含少量高斯噪声的虚拟数据。
# Authors: The scikit-learn developers
# SPDX-License-Identifier: BSD-3-Clause
import numpy as np
rng = np.random.RandomState(1)
X = np.linspace(0, 6, 100)[:, np.newaxis]
y = np.sin(X).ravel() + np.sin(6 * X).ravel() + rng.normal(0, 0.1, X.shape[0])
使用决策树和 AdaBoost 回归器进行训练与预测#
现在,我们定义分类器并将其拟合到数据上。然后,我们在相同的数据上进行预测,以观察它们的拟合效果。第一个回归器是 max_depth=4 的 DecisionTreeRegressor。第二个回归器是 AdaBoostRegressor,它使用 max_depth=4 的 DecisionTreeRegressor 作为基学习器,并设定 n_estimators=300 来构建模型。
from sklearn.ensemble import AdaBoostRegressor
from sklearn.tree import DecisionTreeRegressor
regr_1 = DecisionTreeRegressor(max_depth=4)
regr_2 = AdaBoostRegressor(
DecisionTreeRegressor(max_depth=4), n_estimators=300, random_state=rng
)
regr_1.fit(X, y)
regr_2.fit(X, y)
y_1 = regr_1.predict(X)
y_2 = regr_2.predict(X)
绘制结果#
最后,我们绘制图表,对比单个决策树回归器和 AdaBoost 回归器对数据的拟合效果。
import matplotlib.pyplot as plt
import seaborn as sns
colors = sns.color_palette("colorblind")
plt.figure()
plt.scatter(X, y, color=colors[0], label="training samples")
plt.plot(X, y_1, color=colors[1], label="n_estimators=1", linewidth=2)
plt.plot(X, y_2, color=colors[2], label="n_estimators=300", linewidth=2)
plt.xlabel("data")
plt.ylabel("target")
plt.title("Boosted Decision Tree Regression")
plt.legend()
plt.show()

脚本总运行时间:(0 分 0.453 秒)
相关示例