Stacking是指一种混合估计器的方法,在这种策略中,一些估计器分别在一些训练数据上进行拟合(fit),而最终估计器则使用这些基本估计器的堆叠预测结果来进行训练。
在本示例中,我们将不同的回归器堆叠在一起,并使用最终的线性惩罚回归器(inear penalized regressor)来预测输出。我们将每个回归器的性能与堆叠策略进行比较,结果显示Stacking会稍微改善整体性能。
print(__doc__)# 作者: Guillaume Lemaitre # 许可证: BSD 3 clause
plot_regression_results
函数用于绘制预测目标和真实目标。
import matplotlib.pyplot as pltdef plot_regression_results(ax, y_true, y_pred, title, scores, elapsed_time):"""预测目标与真实目标的散点图。"""
ax.plot([y_true.min(), y_true.max()],
[y_true.min(), y_true.max()],'--r', linewidth=2)
ax.scatter(y_true, y_pred, alpha=0.2)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.get_xaxis().tick_bottom()
ax.get_yaxis().tick_left()
ax.spines['left'].set_position(('outward', 10))
ax.spines['bottom'].set_position(('outward', 10))
ax.set_xlim([y_true.min(), y_true.max()])
ax.set_ylim([y_true.min(), y_true.max()])
ax.set_xlabel('Measured')
ax.set_ylabel('Predicted')
extra = plt.Rectangle((0, 0), 0, 0, fc="w", fill=False,
edgecolor='none', linewidth=0)
ax.legend([extra], [scores], loc='upper left')
title = title + '\n Evaluation in {:.2f} seconds'.format(elapsed_time)
ax.set_title(title)
单个数据集上预测器的堆叠
在给定数据集上找到最适合模型有时会很繁琐,Stacking通过组合多个学习器的输出提供了一种替代方法,而无需专门选择模型。堆叠的性能通常接近最佳模型,有时它的性能可能会超出每个模型的预测性能。
在这里,我们组合了3个学习器(线性和非线性),并使用岭回归器将其输出组合在一起。
from sklearn.ensemble import StackingRegressorfrom sklearn.ensemble import RandomForestRegressorfrom sklearn.experimental import enable_hist_gradient_boosting # noqafrom sklearn.ensemble import HistGradientBoostingRegressorfrom sklearn.linear_model import LassoCVfrom sklearn.linear_model import RidgeCV
estimators = [
('Random Forest', RandomForestRegressor(random_state=42)),
('Lasso', LassoCV()),
('Gradient Boosting', HistGradientBoostingRegressor(random_state=0))
]
stacking_regressor = StackingRegressor(
estimators=estimators, final_estimator=RidgeCV()
)
我们使用了波士顿数据集(房价预测)。我们检查每个预测器以及回归器Stacking后的性能。
import timeimport numpy as npfrom sklearn.datasets import load_bostonfrom sklearn.model_selection import cross_validate, cross_val_predict
X, y = load_boston(return_X_y=True)
fig, axs = plt.subplots(2, 2, figsize=(9, 7))
axs = np.ravel(axs)for ax, (name, est) in zip(axs, estimators + [('Stacking Regressor',
stacking_regressor)]):
start_time = time.time()
score = cross_validate(est, X, y,
scoring=['r2', 'neg_mean_absolute_error'],
n_jobs=-1, verbose=0)
elapsed_time = time.time() - start_time
y_pred = cross_val_predict(est, X, y, n_jobs=-1, verbose=0)
plot_regression_results(
ax, y, y_pred,
name,
(r'$R^2={:.2f} \pm {:.2f}$' + '\n' + r'$MAE={:.2f} \pm {:.2f}$')
.format(np.mean(score['test_r2']),
np.std(score['test_r2']),
-np.mean(score['test_neg_mean_absolute_error']),
np.std(score['test_neg_mean_absolute_error'])),
elapsed_time)
plt.suptitle('Single predictors versus stacked predictors')
plt.tight_layout()
plt.subplots_adjust(top=0.9)
plt.show()
![4bcfb920091df03246643f1832e0af95.png](https://i-blog.csdnimg.cn/blog_migrate/a6573dc3bb244c1d3eabbb61055fc051.png)
![8bebc2169c54688e7056ccadf43ff4e7.png](https://i-blog.csdnimg.cn/blog_migrate/4befad0bdfadab386281aaad82539480.png)
下载python源代码:plot_ica_vs_pca.py
下载Jupyter notebook源代码:plot_ica_vs_pca.ipynb
由Sphinx-Gallery生成的画廊
![6d5dde9144f6baad67d29a9d94b1403b.png](https://i-blog.csdnimg.cn/blog_migrate/053eb9aa9f24f14a5f53457f4b68220c.png)
![c2cdab46d65cbde499f5ed3835dbab2e.png](https://i-blog.csdnimg.cn/blog_migrate/8bb8cac69afcda5499f8e37067e0aee1.png)
![941fbd38127a9778f25ab59fea7e6ae0.png](https://i-blog.csdnimg.cn/blog_migrate/de27e67b0c633a403a8b56f4616e1ee9.png)