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

使用dtreeviz绘图报GridSearchCV无estimators_属性报错解决方法

报错根因

出现AttributeError: 'GridSearchCV' object has no attribute 'estimators_'是两个写法错误导致的:

  • clf是GridSearchCV网格搜索实例,不是最终训练完成的随机森林分类器本身,它没有存储单棵决策树的estimators_属性。网格搜索跑完后选出的最优参数对应的训练完成模型,存放在clf.best_estimator_属性下。
  • 属性名书写错误:随机森林模型里,存储所有训练生成的决策树的列表属性是estimators_,n_estimators_是记录模型树总数量的整数参数,不是树对象集合,不能通过索引取单棵树。
修复方案

直接替换绘图部分的代码即可,先取出最优随机森林模型,再从模型的树列表中选目标树绘制:

# 提取网格搜索得到的最优随机森林模型
best_rf_model = clf.best_estimator_

plt.figure(figsize=(20,20))
# 取模型中第一棵决策树绘制,可修改索引值查看其他树
_ = tree.plot_tree(best_rf_model.estimators_[0], feature_names=X_train.columns, filled=True)

如果后续要用dtreeviz做交互式树可视化,传入的树对象同样从best_rf_model.estimators_列表中选取即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 15:24:27