集成方法
系统讲解误差分解与 Bagging、Boosting、Stacking 三大集成范式,在 scikit-learn 中定量验证随机森林降方差、AdaBoost/GBDT 降偏差与折外 Stacking,并纠正来源错贴输出。
学完这一章,你能够
- 系统讲解误差分解与 Bagging、Boosting、Stacking 三大集成范式,在 scikit-learn 中定量验证随机森林降方差、AdaBoost/GBDT 降偏差与折外 Stacking,并纠正来源错贴输出。
集成学习的误差分解与核心优势
单个基学习器往往很快触及性能瓶颈,集成学习通过组合多个具备多样性的基础模型汇聚集体智慧。模型总预测误差可分解为偏差(假设过简单导致的欠拟合)、方差(对训练波动敏感导致的过拟合)与不可约噪声三部分:集成方法通过平均、投票或序贯纠错显著压低方差或偏差,从而在准确率、抗噪鲁棒性与有效假设空间上全面超越单一弱模型。
Bagging 与随机森林:并行自助采样压低方差
Bagging(Bootstrap Aggregating)通过对训练集有放回随机抽样生成多份子样本,并行独立训练多个高方差基学习器(如深决策树),推理时分类投票、回归求均。随机森林在此基础上叠加「节点分裂随机选特征」的双重随机性,进一步去相关、抗过拟合。本站在 420 条含噪非线性分类数据上跨 6 轮自助重采样实测:单棵未剪枝决策树测试概率预测方差高达 0.10604,而随机森林将方差剧烈压缩至 0.00643(降幅超 16 倍),留出准确率亦由单树 0.7937 提升至 Bagging 0.8016、随机森林 0.8254;在鸢尾花 7:3 留出集上 RandomForestClassifier(n_estimators=100, max_depth=5) 测得准确率 1.0000、首棵树深度 4。
Boosting(AdaBoost / GBDT)与 Stacking 元学习
Boosting 采取串行纠错路线,依次训练弱学习器并将后继模型聚焦在前序错分或残差样本上,最终加权组合以大幅降低偏差:AdaBoost 动态提高错分样本权重,梯度提升决策树(GBDT)则让每棵新树拟合当前损失的负梯度残差。注意来源在 GBDT 代码段下错贴了随机森林的打印结果;本站分别实测确认:在含噪二分类上,深度 1 弱树桩留出准确率仅 0.7460,经 AdaBoost 提至 0.7937、GBDT(n_estimators=100, learning_rate=0.1, max_depth=3)进一步提至 0.8095;在鸢尾花留出集上 GBDT 准确率同样达到 1.0000,四维特征重要性精确为 [0.0045, 0.0189, 0.5913, 0.3854](总和 1.0)。
Stacking 将多种异构基学习器(如 KNN、SVM、随机森林)的预测概率作为新特征,再训练第二层元学习器(如逻辑回归)学习最优组合权重;为防第二层过拟合,第一层训练预测必须经由折外交叉验证生成。本站构建 5 折折外 StackingClassifier(基模型 KNN 0.8413、SVC 0.8333、RF 0.8254),元学习器学得三组正向融合权重 [2.0375, 1.8279, 2.0172],在独立留出集测得准确率 0.8175(也印证结构复杂且算力更高时并非总能无条件超越最优单一模型,须凭交叉验证择优)。
三大方法对比、生态工具与工程调参指南
工程落地应先以逻辑回归或单树建立简单基线,再按误差类型选型:高方差过拟合优先尝试 Bagging/随机森林;高偏差欠拟合或表格冲高分优先尝试 Boosting(除 scikit-learn 内置实现外,产业界常用 XGBoost、LightGBM 与擅长类别特征的 CatBoost);竞赛或算力充裕时再审慎尝试 Stacking。调参重点聚焦 n_estimators、learning_rate(小学习率配更多树)与 max_depth。本站在训练集 5 折交叉验证扫描实测:随机森林树数由 1 增至 10、40、80 时,CV 准确率由 0.7551 稳步升至 0.8162、0.8267、0.8437;GBDT 在学习率 0.02/0.1/0.5 下 CV 分别为 0.8231、0.8061、0.8094。下方表格汇总三类范式核心差异。
Bagging、Boosting 与 Stacking 三大集成方法对比
| 特性 | Bagging (如:随机森林) | Boosting (如:GBDT, XGBoost) | Stacking |
| 核心目标 | 主要降低方差,抑制深树过拟合 | 主要降低偏差,把弱学习器提升为强学习器 | 融合异构模型优势,优化二层组合策略 |
| 训练方式 | 并行独立训练各基学习器 | 串行迭代训练,每轮依赖前序残差/权重 | 分层训练:先折外训基模型,再训元学习器 |
| 样本权重 | 平等对待,通过自助采样制造数据扰动 | 动态调整错分样本权重或拟合负梯度 | 通常等权,二层聚焦预测概率特征 |
| 基学习器关系 | 彼此独立,多样性源于样本与特征随机性 | 紧密耦合,顺序纠错共同最小化损失 | 彼此独立,多样性源于不同算法族差异 |
| 优势 | 稳健抗过拟合、天然易于并行加速 | 表格任务预测精度高,特征交互捕捉强 | 理论上可综合多类假设空间互补信息 |
| 劣势 | 对高偏差基模型提升有限,多树占内存 | 对标签噪声较敏感、过深易过拟合、调参多 | 结构复杂、训练开销大、缺乏折外切分易泄露 |
| 典型应用 | RandomForest、Extra-Trees | AdaBoost、GBDT、XGBoost、LightGBM、CatBoost | 数据竞赛与高精度多模型融合系统 |
运行随机森林降方差、AdaBoost/GBDT 提升与折外 Stacking 实测
展开查看收起
"""Independent scikit-learn CPU lab for Bagging (RandomForest), Boosting (AdaBoost/GBDT), Stacking, and hyperparameter sweeps."""
import json
import platform
import numpy as np
from sklearn.datasets import load_iris, make_classification
from sklearn.ensemble import (
AdaBoostClassifier,
BaggingClassifier,
GradientBoostingClassifier,
RandomForestClassifier,
StackingClassifier,
)
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.model_selection import StratifiedKFold, cross_val_score, train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
def run_cases():
cases = []
# 1. Bagging & RandomForest variance reduction vs single unpruned tree + Iris RF check
X_cls, y_cls = make_classification(
n_samples=420, n_features=12, n_informative=6, n_redundant=2,
flip_y=0.08, class_sep=0.95, random_state=42,
)
X_tr, X_te, y_tr, y_te = train_test_split(
X_cls, y_cls, test_size=0.3, random_state=42, stratify=y_cls
)
# Measure test-prediction variance across 6 bootstrap subsamples of X_tr
rng = np.random.default_rng(42)
single_probs, rf_probs = [], []
for s in range(6):
b_idx = rng.integers(0, len(X_tr), size=len(X_tr))
dt = DecisionTreeClassifier(random_state=s).fit(X_tr[b_idx], y_tr[b_idx])
rf_b = RandomForestClassifier(n_estimators=40, max_depth=8, random_state=s).fit(X_tr[b_idx], y_tr[b_idx])
single_probs.append(dt.predict_proba(X_te)[:, 1])
rf_probs.append(rf_b.predict_proba(X_te)[:, 1])
dt_var = round(float(np.mean(np.var(np.asarray(single_probs), axis=0))), 5)
rf_var = round(float(np.mean(np.var(np.asarray(rf_probs), axis=0))), 5)
dt_full = DecisionTreeClassifier(random_state=42).fit(X_tr, y_tr)
bag_full = BaggingClassifier(
estimator=DecisionTreeClassifier(random_state=42),
n_estimators=40, random_state=42,
).fit(X_tr, y_tr)
rf_full = RandomForestClassifier(n_estimators=80, max_depth=8, random_state=42).fit(X_tr, y_tr)
dt_acc = round(float(accuracy_score(y_te, dt_full.predict(X_te))), 4)
bag_acc = round(float(accuracy_score(y_te, bag_full.predict(X_te))), 4)
rf_acc = round(float(accuracy_score(y_te, rf_full.predict(X_te))), 4)
# Iris RandomForest verification
iris = load_iris()
Xi_tr, Xi_te, yi_tr, yi_te = train_test_split(iris.data, iris.target, test_size=0.3, random_state=42)
rf_iris = RandomForestClassifier(n_estimators=100, max_depth=5, random_state=42).fit(Xi_tr, yi_tr)
iris_rf_acc = round(float(accuracy_score(yi_te, rf_iris.predict(Xi_te))), 4)
first_tree_depth = int(rf_iris.estimators_[0].get_depth())
c1_ok = rf_var < dt_var * 0.4 and rf_acc > dt_acc and bag_acc > dt_acc and iris_rf_acc >= 0.95 and first_tree_depth <= 5
cases.append(dict(
name="bagging_variance_reduction_and_rf",
inputs=dict(n_samples=420, bootstrap_runs=8, n_estimators=100),
prerequisites="在含噪非线性二分类与 Iris 数据集对比单棵决策树、Bagging 与 RandomForest",
action="验证随机森林预测概率方差降至单树 40% 以下、Bagging/RF 留出准确率均超越单树,且 Iris 随机森林 >=0.95、首树深度 <=5。",
expected=dict(rf_variance_lt_40pct_dt=True, ensembles_beat_single_tree=True, iris_rf_ge_95=True),
actual=dict(rf_variance_lt_40pct_dt=(rf_var < dt_var * 0.4), ensembles_beat_single_tree=(rf_acc > dt_acc and bag_acc > dt_acc), iris_rf_ge_95=(iris_rf_acc >= 0.95)),
measurements=dict(dt_pred_var=dt_var, rf_pred_var=rf_var, dt_acc=dt_acc, bag_acc=bag_acc, rf_acc=rf_acc, iris_rf_acc=iris_rf_acc, iris_first_tree_depth=first_tree_depth),
passed=c1_ok,
))
# 2. Boosting (AdaBoost + GradientBoosting) bias reduction & feature importances
stump = DecisionTreeClassifier(max_depth=1, random_state=42).fit(X_tr, y_tr)
ada = AdaBoostClassifier(n_estimators=80, learning_rate=0.5, random_state=42).fit(X_tr, y_tr)
gb = GradientBoostingClassifier(n_estimators=100, learning_rate=0.1, max_depth=3, random_state=42).fit(X_tr, y_tr)
stump_acc = round(float(accuracy_score(y_te, stump.predict(X_te))), 4)
ada_acc = round(float(accuracy_score(y_te, ada.predict(X_te))), 4)
gb_acc = round(float(accuracy_score(y_te, gb.predict(X_te))), 4)
gb_iris = GradientBoostingClassifier(n_estimators=100, learning_rate=0.1, max_depth=3, random_state=42).fit(Xi_tr, yi_tr)
iris_gb_acc = round(float(accuracy_score(yi_te, gb_iris.predict(Xi_te))), 4)
imp_sum = round(float(np.sum(gb_iris.feature_importances_)), 6)
c2_ok = ada_acc > stump_acc and gb_acc > stump_acc and iris_gb_acc >= 0.95 and abs(imp_sum - 1.0) < 1e-5
cases.append(dict(
name="boosting_adaboost_and_gbdt",
inputs=dict(weak_depth=1, n_estimators=100, learning_rate=0.1, gb_max_depth=3),
prerequisites="对比深度 1 弱决策树桩与 AdaBoost / GradientBoostingClassifier 串行纠错提升",
action="验证 AdaBoost 与 GBDT 均显著超越弱树桩基准,Iris GBDT 准确率 >=0.95 且特征重要性归一化总和为 1.0。",
expected=dict(boosting_beats_stump=True, iris_gb_ge_95=True, importances_sum_one=True),
actual=dict(boosting_beats_stump=(ada_acc > stump_acc and gb_acc > stump_acc), iris_gb_ge_95=(iris_gb_acc >= 0.95), importances_sum_one=(abs(imp_sum - 1.0) < 1e-5)),
measurements=dict(stump_acc=stump_acc, ada_acc=ada_acc, gb_acc=gb_acc, iris_gb_acc=iris_gb_acc, iris_gb_importances=[round(float(v), 4) for v in gb_iris.feature_importances_]),
passed=c2_ok,
))
# 3. StackingClassifier with out-of-fold cross-validated meta-features
base_estimators = [
("knn", Pipeline([("scaler", StandardScaler()), ("clf", KNeighborsClassifier(n_neighbors=7))])),
("svc", Pipeline([("scaler", StandardScaler()), ("clf", SVC(probability=True, random_state=42))])),
("rf", RandomForestClassifier(n_estimators=50, max_depth=8, random_state=42)),
]
base_accs = {}
for name, est in base_estimators:
est.fit(X_tr, y_tr)
base_accs[name] = round(float(accuracy_score(y_te, est.predict(X_te))), 4)
stack = StackingClassifier(
estimators=base_estimators,
final_estimator=LogisticRegression(max_iter=1000),
cv=StratifiedKFold(n_splits=5, shuffle=True, random_state=42),
stack_method="predict_proba",
)
stack.fit(X_tr, y_tr)
stack_acc = round(float(accuracy_score(y_te, stack.predict(X_te))), 4)
meta_coef_len = int(stack.final_estimator_.coef_.size)
c3_ok = stack_acc >= 0.80 and meta_coef_len == 3
cases.append(dict(
name="stacking_out_of_fold_meta_learner",
inputs=dict(base_models=["knn", "svc", "rf"], meta_model="LogisticRegression", cv=5),
prerequisites="StackingClassifier 内部用 5 折折外概率构造第二层元特征避免泄露",
action="验证二层堆叠元学习器学得 3 个基模型组合权重并在留出测试集取得 >=0.80 准确率。",
expected=dict(meta_weights_count=3, stack_acc_ge_80=True),
actual=dict(meta_weights_count=meta_coef_len, stack_acc_ge_80=stack_acc >= 0.80),
measurements=dict(base_test_accs=base_accs, stack_test_acc=stack_acc, meta_coefs=[round(float(v), 4) for v in stack.final_estimator_.coef_.ravel()]),
passed=c3_ok,
))
# 4. Key ensemble hyperparameters sweep inside training CV (n_estimators, learning_rate, max_depth)
cv5 = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
rf_sweep = {}
for n_est in (1, 10, 40, 80):
rf_sweep[str(n_est)] = round(float(cross_val_score(
RandomForestClassifier(n_estimators=n_est, max_depth=8, random_state=42),
X_tr, y_tr, cv=cv5, scoring="accuracy",
).mean()), 4)
gb_sweep = {}
for lr in (0.02, 0.1, 0.5):
gb_sweep[str(lr)] = round(float(cross_val_score(
GradientBoostingClassifier(n_estimators=50, learning_rate=lr, max_depth=3, random_state=42),
X_tr, y_tr, cv=cv5, scoring="accuracy",
).mean()), 4)
c4_ok = rf_sweep["80"] > rf_sweep["1"] and rf_sweep["40"] > rf_sweep["1"] and max(gb_sweep.values()) >= 0.80
cases.append(dict(
name="ensemble_hyperparameter_sensitivity",
inputs=dict(rf_n_estimators=[1, 10, 40, 80], gb_learning_rates=[0.02, 0.1, 0.5]),
prerequisites="仅在训练集 5 折交叉验证中扫描 n_estimators 与 learning_rate",
action="验证随机森林树数由 1 增至 40/80 时交叉验证准确率显著提升,并记录不同学习率下 GBDT 验证分数。",
expected=dict(more_trees_beats_single_tree=True, gb_best_cv_ge_80=True),
actual=dict(more_trees_beats_single_tree=(rf_sweep["80"] > rf_sweep["1"] and rf_sweep["40"] > rf_sweep["1"]), gb_best_cv_ge_80=(max(gb_sweep.values()) >= 0.80)),
measurements=dict(rf_cv_by_n_estimators=rf_sweep, gb_cv_by_learning_rate=gb_sweep),
passed=c4_ok,
))
payload = dict(
version=platform.python_version(),
system=platform.system(),
cases=cases,
)
print(json.dumps(payload, ensure_ascii=False))
if __name__ == "__main__":
run_cases()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
强基学习器(如深随机森林)在训练集上的拟合预测近乎完美,元学习器会过度信任过拟合最严重的基模型并在测试集崩溃;必须通过交叉验证折外预测(out-of-fold)生成无偏元特征。