蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行随机森林降方差、AdaBoost/GBDT 提升与折外 Stacking 实测

PYTHONWindows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。explore-model-optimization-integrated-approaches.py
explore-model-optimization-integrated-approaches.py171 行
"""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()
本例需在 Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。

入口文件:projects/ml-model-optimization-integrated-approaches-lab/explore-model-optimization-integrated-approaches.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-model-optimization-integrated-approaches.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:机器学习

课程关联工程包(登记关联58章) · 含当前章节或实例 · mbskycom202612a449.zip

下载课程关联工程包:机器学习

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a485.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习