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

运行随机森林分类投票、特征重要性、超参数约束与回归缩放不变性实验

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-random-forest.py
explore-random-forest.py180 行
"""Independent scikit-learn Random Forest classification, feature importance, hyperparameters & scale-invariance lab."""
import json
import platform

import numpy as np
import pandas as pd
import sklearn
from sklearn.datasets import load_diabetes, load_iris
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
from sklearn.metrics import accuracy_score, classification_report, r2_score
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier


def run_cases():
    cases = []

    # 1. Iris 70/30 classification & ensemble majority/probability voting
    iris = load_iris()
    X, y = iris.data, iris.target
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
    rf_clf = RandomForestClassifier(n_estimators=100, max_depth=5, random_state=42)
    rf_clf.fit(X_train, y_train)
    y_pred = rf_clf.predict(X_test)
    acc = round(float(accuracy_score(y_test, y_pred)), 4)
    report = classification_report(y_test, y_pred, target_names=iris.target_names, output_dict=True)

    # Verify ensemble prediction equals average of individual tree probabilities
    tree_probas = np.mean([est.predict_proba(X_test) for est in rf_clf.estimators_], axis=0)
    proba_diff = float(np.max(np.abs(tree_probas - rf_clf.predict_proba(X_test))))
    vote_match = bool(np.array_equal(np.argmax(tree_probas, axis=1), y_pred))

    # Compare against single decision tree on noisy synthetic binary data for variance reduction
    rng = np.random.default_rng(42)
    X_syn = rng.normal(size=(400, 10))
    logits = 1.6 * X_syn[:, 0] - 1.3 * X_syn[:, 1] + 0.9 * X_syn[:, 2] * X_syn[:, 3]
    y_syn = (logits + rng.normal(scale=1.1, size=400) > 0).astype(int)
    Xs_tr, Xs_te, ys_tr, ys_te = train_test_split(X_syn, y_syn, test_size=0.3, random_state=42)
    dt_acc = round(float(accuracy_score(ys_te, DecisionTreeClassifier(random_state=42).fit(Xs_tr, ys_tr).predict(Xs_te))), 4)
    rf_syn_acc = round(float(accuracy_score(ys_te, RandomForestClassifier(n_estimators=100, random_state=42).fit(Xs_tr, ys_tr).predict(Xs_te))), 4)

    c1_ok = acc == 1.0 and proba_diff < 1e-12 and vote_match and rf_syn_acc > dt_acc
    cases.append(dict(
        name="iris_rf_classification_and_voting",
        inputs=dict(dataset="load_iris", test_size=0.3, n_estimators=100, max_depth=5, random_state=42),
        prerequisites="RandomForestClassifier 在鸢尾花 70/30 划分与含噪非线性合成数据上的集成预测",
        action="验证随机森林在 Iris 测试集准确率、单树概率聚合一致性及抗过拟合优势。",
        expected=dict(iris_acc=1.0, proba_agg_exact=True, rf_beats_single_tree=True),
        actual=dict(iris_acc=acc, proba_agg_exact=(proba_diff < 1e-12 and vote_match), rf_beats_single_tree=(rf_syn_acc > dt_acc)),
        measurements=dict(
            iris_test_samples=int(len(y_test)),
            iris_accuracy=acc,
            iris_macro_f1=round(float(report["macro avg"]["f1-score"]), 4),
            max_proba_agg_diff=round(proba_diff, 12),
            noisy_single_tree_acc=dt_acc,
            noisy_rf_acc=rf_syn_acc,
        ),
        passed=c1_ok,
    ))

    # 2. Feature importance ranking on Iris
    imp_df = pd.DataFrame({
        "feature": iris.feature_names,
        "importance": rf_clf.feature_importances_,
    }).sort_values("importance", ascending=False).reset_index(drop=True)
    imp_sum = round(float(imp_df["importance"].sum()), 6)
    top2 = imp_df["feature"].iloc[:2].tolist()
    petal_share = round(float(imp_df[imp_df["feature"].str.contains("petal")]["importance"].sum()), 4)
    c2_ok = abs(imp_sum - 1.0) < 1e-6 and all("petal" in f for f in top2) and petal_share > 0.80
    cases.append(dict(
        name="iris_feature_importances_ranking",
        inputs=dict(n_features=4, model="RandomForestClassifier(100, max_depth=5)"),
        prerequisites="基于不纯度下降的内置 feature_importances_ 评估",
        action="验证特征重要性总和为 1 且花瓣长度与花瓣宽度位居前两位。",
        expected=dict(importance_sums_to_1=True, top2_are_petal=True, petal_share_gt_80pct=True),
        actual=dict(importance_sums_to_1=(abs(imp_sum - 1.0) < 1e-6), top2_are_petal=all("petal" in f for f in top2), petal_share_gt_80pct=(petal_share > 0.80)),
        measurements=dict(
            ranked_features=[dict(feature=r["feature"], importance=round(float(r["importance"]), 4)) for _, r in imp_df.iterrows()],
            petal_total_importance=petal_share,
            importance_sum=imp_sum,
        ),
        passed=c2_ok,
    ))

    # 3. Hyperparameters (n_estimators, max_depth, max_features, min_samples_split, min_samples_leaf, bootstrap)
    rf_oob = RandomForestClassifier(n_estimators=100, bootstrap=True, oob_score=True, max_features="sqrt", random_state=42)
    rf_oob.fit(Xs_tr, ys_tr)
    oob_acc = round(float(rf_oob.oob_score_), 4)

    rf_shallow = RandomForestClassifier(n_estimators=50, max_depth=2, min_samples_split=10, min_samples_leaf=5, random_state=42).fit(Xs_tr, ys_tr)
    rf_deep = RandomForestClassifier(n_estimators=50, max_depth=None, min_samples_split=2, min_samples_leaf=1, random_state=42).fit(Xs_tr, ys_tr)
    shallow_max_depth = int(max(est.get_depth() for est in rf_shallow.estimators_))
    deep_max_depth = int(max(est.get_depth() for est in rf_deep.estimators_))
    shallow_min_leaf = int(min(est.tree_.n_node_samples[est.tree_.children_left == -1].min() for est in rf_shallow.estimators_))

    # Check bootstrap=False rejects oob_score=True, and legacy max_features='auto' raises ValueError in sklearn 1.9
    auto_rejected = False
    try:
        RandomForestClassifier(max_features="auto").fit(X_train, y_train)
    except ValueError:
        auto_rejected = True

    noboot_oob_rejected = False
    try:
        RandomForestClassifier(bootstrap=False, oob_score=True).fit(X_train, y_train)
    except ValueError:
        noboot_oob_rejected = True

    rf_noboot = RandomForestClassifier(n_estimators=50, bootstrap=False, max_features=2, random_state=42).fit(X_train, y_train)
    noboot_acc = round(float(accuracy_score(y_test, rf_noboot.predict(X_test))), 4)

    c3_ok = (
        shallow_max_depth <= 2
        and deep_max_depth > shallow_max_depth
        and shallow_min_leaf >= 5
        and auto_rejected
        and noboot_oob_rejected
        and oob_acc >= 0.75
    )
    cases.append(dict(
        name="hyperparameters_and_max_features_api",
        inputs=dict(shallow_cfg=dict(max_depth=2, min_samples_split=10, min_samples_leaf=5), bootstrap_oob=True),
        prerequisites="核对六项核心超参数约束与 scikit-learn 1.9 max_features='auto' 废弃边界",
        action="验证深度与叶样本约束、OOB 袋外评估、bootstrap=False 限制及 max_features='auto' 抛 ValueError。",
        expected=dict(depth_constrained=True, leaf_min_ge_5=True, auto_raises_value_error=True, noboot_oob_raises=True),
        actual=dict(depth_constrained=(shallow_max_depth <= 2 and deep_max_depth > 2), leaf_min_ge_5=(shallow_min_leaf >= 5), auto_raises_value_error=auto_rejected, noboot_oob_raises=noboot_oob_rejected),
        measurements=dict(
            shallow_max_depth=shallow_max_depth,
            deep_max_depth=deep_max_depth,
            shallow_min_leaf_samples=shallow_min_leaf,
            oob_score=oob_acc,
            noboot_iris_acc=noboot_acc,
        ),
        passed=c3_ok,
    ))

    # 4. Regression tree-averaging & feature scale invariance
    diab = load_diabetes()
    Xd_tr, Xd_te, yd_tr, yd_te = train_test_split(diab.data, diab.target, test_size=0.25, random_state=42)
    rf_reg = RandomForestRegressor(n_estimators=80, max_depth=8, random_state=42).fit(Xd_tr, yd_tr)
    reg_pred = rf_reg.predict(Xd_te)
    manual_avg = np.mean([est.predict(Xd_te) for est in rf_reg.estimators_], axis=0)
    reg_avg_diff = float(np.max(np.abs(reg_pred - manual_avg)))
    reg_r2 = round(float(r2_score(yd_te, reg_pred)), 4)

    # Scale invariance check: multiply features by distinct positive scales
    scales = np.array([1000.0, 0.01, 50.0, 200.0])
    rf_scaled = RandomForestClassifier(n_estimators=100, max_depth=5, random_state=42).fit(X_train * scales, y_train)
    scale_pred_identical = bool(np.array_equal(rf_clf.predict(X_test), rf_scaled.predict(X_test * scales)))

    c4_ok = reg_avg_diff < 1e-11 and reg_r2 > 0.40 and scale_pred_identical
    cases.append(dict(
        name="rf_regression_averaging_and_scale_invariance",
        inputs=dict(regression_dataset="load_diabetes", n_estimators=80, feature_scales=[1000.0, 0.01, 50.0, 200.0]),
        prerequisites="RandomForestRegressor 树预测均值聚合及分类器对单调特征缩放的不变性",
        action="验证回归森林预测精确等于单棵树均值,且对特征施加差异化正缩放后分类预测完全不变。",
        expected=dict(reg_avg_exact=True, reg_r2_gt_04=True, scale_invariant=True),
        actual=dict(reg_avg_exact=(reg_avg_diff < 1e-11), reg_r2_gt_04=(reg_r2 > 0.40), scale_invariant=scale_pred_identical),
        measurements=dict(
            reg_max_avg_diff=round(reg_avg_diff, 12),
            diabetes_test_r2=reg_r2,
            scale_invariant_predictions=scale_pred_identical,
        ),
        passed=c4_ok,
    ))

    payload = dict(
        version=platform.python_version(),
        sklearn=sklearn.__version__,
        numpy=np.__version__,
        pandas=pd.__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-random-forest-lab/explore-random-forest.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-random-forest.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章) · 含当前章节或实例 · mbskycom202612a498.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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