You need to enable JavaScript to run this app. 如何绘制GridSearchCV封装Pipeline输出的最优决策树模型
优惠活动
大模型
产品
解决方案
定价
更多

如何绘制GridSearchCV封装Pipeline输出的最优决策树模型

报错原因与解决方案

报错根因

GridSearchCV的best_estimator_返回的是完整的Pipeline实例,包含你定义的标准化、决策树两个步骤,而plot_tree仅支持接收拟合完成的决策树类评估器作为输入,直接传入Pipeline就会触发未拟合的报错。

解决方法

从最优Pipeline中提取嵌套的决策树模型即可:Pipeline提供了named_steps属性,你可以通过预先定义的决策树步骤名regressor,取出已经拟合完成的决策树对象,再传给plot_tree。

另外你代码里的feature_names参数赋值也存在问题,4维输入特征对应要传长度为4的特征名列表,不能直接写('X'),否则会触发维度不匹配报错,同步修正如下。

修正后可运行代码

from sklearn.preprocessing import StandardScaler
from sklearn.tree import DecisionTreeRegressor, plot_tree
from sklearn.pipeline import Pipeline
from sklearn.model_selection import GridSearchCV
import numpy as np
from matplotlib import pyplot as plt

# Dummy data
X= [[1,2,3,5], [3,4,5,6], [6,7,8,9], [1,2,3,5], [3,4,5,6], [6,7,8,9]]
y= [50,70,80,2,5,6]

scr = StandardScaler()
dtree = DecisionTreeRegressor(random_state=100)

pipeline_tree = Pipeline([
    ('scaler', scr),
    ('regressor', dtree)
])

param_grid_tree = [{
    'regressor__max_depth': [2, 3],
    'regressor__min_samples_split': [2, 3],
}]
GridSearchCV_tree = GridSearchCV(estimator=pipeline_tree,
                                 param_grid=param_grid_tree, cv=2)


Dtree = GridSearchCV_tree.fit(X, y)

# 核心修改:从最优Pipeline中取出决策树模型,修正特征名参数
plot_tree(Dtree.best_estimator_.named_steps['regressor'], 
          max_depth=5,
          impurity=True,
          feature_names=['f1','f2','f3','f4'],
          precision=1, filled=True)
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 09:15:04