管道内决策树的可视化
Posted
技术标签:
【中文标题】管道内决策树的可视化【英文标题】:Visualization of a decision tree inside a pipeline 【发布时间】:2019-12-18 21:52:30 【问题描述】:我想用export_graphviz
可视化我的决策树,但是我不断收到以下错误:
File "C:\Users\User\AppData\Local\Continuum\anaconda3\envs\data_science\lib\site-packages\sklearn\utils\validation.py", line 951, in check_is_fitted
raise NotFittedError(msg % 'name': type(estimator).__name__)
NotFittedError: This Pipeline instance is not fitted yet. Call 'fit' with appropriate arguments before using this method.
我很确定我的管道已安装,因为我在代码中调用了 predict ,它工作得很好。这是有问题的代码:
from sklearn.tree import DecisionTreeRegressor
import pandas as pd
import numpy as np
from sklearn.pipeline import Pipeline
from sklearn.model_selection import train_test_split
from sklearn.tree import export_graphviz
#Parameters for model building an reproducibility
state = 13
data_age.dropna(inplace=True)
X_age = data_age.iloc[:,0:77]
y_age = data_age.iloc[:,77]
X = X_age
y = y_age
#split between testing and training set
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state= state)
# Pipeline with the regressor
regressors = [DecisionTreeRegressor(random_state = state)]
for reg in regressors:
steps=[('regressor', reg)]
pipeline = Pipeline(steps) #seed that controls the random grid search
#Train the model
pipeline.set_params(regressor__max_depth = 5, regressor__min_samples_split =5, regressor__min_samples_leaf = 5).fit(X_train, y_train)
pred = pipeline.predict(X_test)
pipeline.score(X_test, y_test)
export_graphviz(pipeline, out_file='tree.dot')
我知道我在这里并不真正需要管道,但我仍然想了解问题是什么以供将来参考,并能够在已安装的管道内绘制决策树。
【问题讨论】:
【参考方案1】:export_graphviz
的签名是export_graphviz(decision_tree, ...)
,可以在documentation 中看到。
因此,您应该将决策树作为参数传递给 export_graphviz
函数,而不是您的管道。
您还可以在source code 中看到export_grpahviz
正在调用check_is_fitted(decision_tree, 'tree_')
方法。
【讨论】:
【参考方案2】:因此,根据 Farseer 的回答,最后一行必须是:
#Train the model
pipeline.set_params(regressor__max_depth = 5, regressor__min_samples_split =5, regressor__min_samples_leaf = 5).fit(X_train, y_train)
pred = pipeline.predict(X_test)
pipeline.score(X_test, y_test)
#export as a .dot file
export_graphviz(regressors[0], out_file='tree.dot')
现在它可以工作了。
【讨论】:
以上是关于管道内决策树的可视化的主要内容,如果未能解决你的问题,请参考以下文章
R语言使用party包中的ctree函数构建条件推理决策树(Conditional inference trees)使用plot函数可视化训练好的条件推理决策树条件推理决策树的叶子节点的阴影区域表
R语言使用rpart包构建决策树模型选择合适的树大小(复杂度)检查决策树对象的cptable内容(树的大小由分裂次数定义预测误差)使用plotcp函数可视化决策树复杂度参数与交叉验证错误的关系