Plot best decision tree with pipeline and GridsearchCV(用管道和网格搜索绘制最佳决策树)
本文介绍了用管道和网格搜索绘制最佳决策树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个使用决策树作为估计器的流水线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中阅读有关它的更多信息。
这篇关于用管道和网格搜索绘制最佳决策树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
编程基础网
本文标题为:用管道和网格搜索绘制最佳决策树
基础教程推荐
猜你喜欢
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
