随机森林
核对随机森林 Bagging 自助采样与特征随机性、六项核心超参数及 scikit-learn 1.9 的 max_features 边界、Iris 分类与特征重要性、回归均值聚合及缩放不变性。
学完这一章,你能够
- 核对随机森林 Bagging 自助采样与特征随机性、六项核心超参数及 scikit-learn 1.9 的 max_features 边界、Iris 分类与特征重要性、回归均值聚合及缩放不变性。
集成学习、Bagging 与双重随机性
单个决策树虽然直观,但容易受训练样本微扰影响而产生高方差。随机森林(Random Forest)属于集成学习算法,它并行构建多棵彼此存在差异的决策树,并汇总群体判断作为最终输出:分类任务采用多数投票(或在 scikit-learn 中对各树预测概率求平均后取最大类),回归任务则对所有单树预测值取算术平均。
随机森林的多样性来自两项核心机制:其一是 Bagging(自助聚合),通过有放回抽样(Bootstrap)为每棵树生成互不完全相同的训练子集,再独立训练并聚合;其二是特征随机性,在每个节点寻找分裂点时仅从随机抽取的特征子集中择优,避免少数强特征垄断所有树的顶层结构。双重随机性大幅降低了单棵树之间的相关性,从而在聚合后显著压低方差、抑制过拟合。
工作流程与关键超参数核对
标准训练流程为:反复执行有放回采样构建子数据集、在节点分裂时按随机特征子集生长单棵决策树、将全部树保存为森林,预测阶段汇总全部树的投票或均值。在 scikit-learn 1.9.1 中调优需特别核对六项关键超参数(见下表)及一项版本变更:旧资料常写 max_features='auto',但现代 scikit-learn 已移除 'auto' 选项并在传入时直接抛出 ValueError,分类任务应使用默认 'sqrt'、整数或比例浮点数;此外,只有当 bootstrap=True 时才支持开启 oob_score=True 做袋外估计(本站实测 bootstrap=False 搭配 oob_score=True 会触发 ValueError,开启袋外估计在含噪合成数据上测得 oob_score=0.7893)。限制 max_depth=2、min_samples_split=10、min_samples_leaf=5 后,实测全森林最大树深被压制在 2(不限制时达 13)且所有叶节点样本数均 >=5。
鸢尾花分类、特征重要性与回归实测
在 150 条样本、4 项特征、3 个类别的鸢尾花(Iris)数据集上按 70%/30% 划分并固定 random_state=42,训练 RandomForestClassifier(n_estimators=100, max_depth=5, random_state=42) 后,本站实测 45 条测试样本准确率为 1.0000、宏平均 F1 为 1.0000,且森林 predict_proba 与 100 棵基树预测概率手算均值的最大误差为 0.0。在额外构建的 400 条含噪非线性合成数据上,单棵决策树测试准确率为 0.8000,100 棵树随机森林提升至 0.8083。
随机森林在训练过程中同步累积各特征在节点分裂带来的不纯度下降,直接提供 feature_importances_。本站对上述 Iris 模型实测特征重要性总和精确为 1.0,排序依次为花瓣宽度(petal width,0.4366)、花瓣长度(petal length,0.4173)、花萼长度(sepal length,0.1046)与花萼宽度(sepal width,0.0415),花瓣两项合计占比达 85.39%,与植物形态区分依据吻合。针对回归任务,本站在糖尿病数据集(load_diabetes)上训练 80 棵树的 RandomForestRegressor,测试集 R² 达 0.4549 且预测结果与 80 棵单树预测均值误差为 0.0。
优缺点权衡与典型应用场景
随机森林兼具较高预测精度、抗过拟合、内置特征重要性及易于多核并行等优势,且因决策树基于特征阈值排序分裂,对特征尺度单调缩放天然不敏感——本站对 Iris 四列特征分别乘以 [1000, 0.01, 50, 200] 后重训同参数森林,测试集预测与未缩放版本完全一致。其主要局限在于成百上千棵树构成黑箱难以像单树一样直读规则,同时树数量庞大时会增大训练/推理耗时与内存开销。工程中常用于风控与医疗等表格分类、房价与销量回归以及特征筛选(注意高基数类别或含缺失值的原生处理仍需结合对应版本分裂支持与预处理策略验证)。
RandomForestClassifier 核心超参数核对
| 参数名 | 含义 | 典型值与影响 | 直观类比 |
| n_estimators | 森林包含的决策树总数 | 默认 100;增大通常降低方差、提高稳定性,但线性增加训练与内存开销。 | 评审委员会人数:人越多结论越稳,开会成本也越高。 |
| max_depth | 单棵决策树允许生长的最大深度 | 默认 None(不限深);限制深度(如 2 或 5)可防止单树过度记忆噪声。 | 限定每位委员的追问层数,避免钻牛角尖。 |
| max_features | 每次节点分裂随机考察的最大特征数 | 分类默认 'sqrt',也可传整数/比例;注意 scikit-learn 1.9 已移除 'auto'(传参抛 ValueError)。 | 每次表决只随机审视部分维度,提升树间多样性。 |
| min_samples_split | 内部节点继续分裂所需的最小样本数 | 默认 2;增大后树分裂更保守,有助于抑制细碎过拟合分支。 | 小组人数达到门槛才允许继续细分讨论。 |
| min_samples_leaf | 每个叶节点必须保留的最小样本数 | 默认 1;提高(如实测设为 5)使决策边界更平滑。 | 每条最终结论至少需要足够样本支撑。 |
| bootstrap | 构建各树时是否采用有放回自助采样 | 默认 True(可配合 oob_score=True);设为 False 则用全量样本建树且禁用 OOB。 | 是否允许同一样本重复入选训练子集,是 Bagging 核心开关。 |
运行随机森林分类投票、特征重要性、超参数约束与回归缩放不变性实验
展开查看收起
"""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()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
scikit-learn 从 1.3 起移除了冗余且易混淆的 'auto' 字符串选项;分类任务应改用默认的 'sqrt'(或显式传入整数/浮点比例),回归任务若需考虑全部特征则传 1.0 或 None。