You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何可视化含56个estimator的随机森林模型中的最优决策树?

可视化随机森林中的“最优”决策树

首先要明确:随机森林里的单棵树没有绝对的“最优”,通常我们会基于袋外(OOB)样本的预测性能来筛选表现最好的树——因为随机森林训练时每个树只用到了部分训练样本,剩下的未被选中的样本就是OOB样本,可以用来评估单棵树的泛化能力。

步骤1:计算每棵树的OOB准确率

遍历所有estimator,用OOB样本计算它们的预测准确率:

import numpy as np
from sklearn.metrics import accuracy_score

# 获取每棵树对应的OOB样本索引(未被用于训练该树的样本)
oob_indices = []
for tree in tr_classifier.estimators_:
    # 生成训练时被采样的样本索引,取补集得到OOB样本
    sampled_indices = tree.random_state.permutation(len(X))[:tree.n_samples_]
    oob_idx = np.setdiff1d(np.arange(len(X)), sampled_indices)
    oob_indices.append(oob_idx)

# 计算每棵树在OOB样本上的准确率
oob_accuracies = []
for idx, tree in enumerate(tr_classifier.estimators_):
    oob_X = X.iloc[oob_indices[idx]]
    oob_y = y.iloc[oob_indices[idx]]  # y为你的目标变量
    y_pred = tree.predict(oob_X)
    acc = accuracy_score(oob_y, y_pred)
    oob_accuracies.append(acc)

步骤2:定位准确率最高的树

# 找出OOB准确率最高的树的索引
best_tree_idx = np.argmax(oob_accuracies)
print(f"最优树索引:{best_tree_idx},OOB准确率:{oob_accuracies[best_tree_idx]:.4f}")

步骤3:可视化最优树

复用你原有的可视化代码,替换索引为筛选出的最优树索引:

import matplotlib.pyplot as plt
from sklearn.tree import plot_tree

fig = plt.figure(figsize=(15, 10))  # 可根据树的复杂度调整尺寸
plot_tree(tr_classifier.estimators_[best_tree_idx], 
          feature_names=X.columns,
          class_names='IPSS-R', 
          filled=True, impurity=True, 
          rounded=True)
plt.show()

补充说明

如果你的随机森林是回归任务,只需把accuracy_score换成mean_squared_error等回归评估指标即可。若你有独立验证集,也可以用验证集的性能替代OOB样本进行筛选,只需将代码中的OOB数据替换为验证集数据。

内容的提问来源于stack exchange,提问作者Dharmini

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 17:02:19