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

如何解决AttributeError: 'RandomForestRegressor'对象无'tree_'属性问题?

问题原因

export_graphviz工具只能处理单个决策树模型,而你用的RandomForestRegressor是集成模型,由多棵独立的决策树组成,它本身没有tree_属性——这个属性是单棵决策树的专属属性,随机森林的所有子树都存在estimators_列表里,所以直接把随机森林模型传给export_graphviz会触发这个报错。

解决办法

从训练好的随机森林中提取单棵子树,再用export_graphviz导出可视化:

修改后的完整代码

from sklearn.tree import export_graphviz
from IPython import display
from sklearn.ensemble import RandomForestRegressor

m = RandomForestRegressor(n_estimators=5, max_depth=3, bootstrap=False, n_jobs=-1)
m.fit(x_train, y_train)

# 提取随机森林中的第一棵子树
single_tree = m.estimators_[0]

str_tree = export_graphviz(single_tree, 
                          out_file=None,
                          feature_names=data.columns[2:4], 
                          filled=True,
                          special_characters=True,
                          rotate=True,
                          precision=1)

display.display(str_tree)

额外说明

如果你想查看随机森林里的多棵树,可以循环遍历estimators_列表:

# 遍历所有5棵子树,逐个导出可视化
for idx, tree in enumerate(m.estimators_):
    str_tree = export_graphviz(tree, 
                              out_file=None,
                              feature_names=data.columns[2:4], 
                              filled=True,
                              special_characters=True,
                              rotate=True,
                              precision=1)
    print(f"第{idx+1}棵树:")
    display.display(str_tree)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 07:40:58