用管道和网格搜索绘制最佳决策树 [英] Plot best decision tree with pipeline and GridsearchCV

查看:22
本文介绍了用管道和网格搜索绘制最佳决策树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用决策树作为估计器的流水线GridearchCV

现在我想绘制与GridearchCV的Best_Estiator相对应的决策树

有一些关于堆栈溢出的回复,但没有人考虑在GridearchCV内建立管道

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


#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)


plot_tree(Dtree.best_estimator_, max_depth=5,
          impurity=True,
          feature_names=('X'),
          precision=1, filled=True)

我得到

NotFittedError: This Pipeline instance is not fitted yet. Call 'fit' with appropriate arguments before using this estimator.

有什么想法吗?

推荐答案

由于您的估计器是Pipeline对象,best_estimator_属性也将返回管道。您必须通过对步骤编制索引来使用回归工具进一步访问正确的步骤,例如:

plot_tree(
    Dtree.best_estimator_['regressor'],  # <-- added indexing here
    max_depth=5,
    impurity=True,
    feature_names=['X1', 'X2', 'X3', 'X4'],   # changed this argument to make it work properly
    precision=1,
    filled=True
)

有关访问管道步骤的不同方法,请参阅user guide

如果您想知道为什么错误消息显示管道未安装,您可以在我的回答here中阅读有关它的更多信息。

这篇关于用管道和网格搜索绘制最佳决策树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆