**之后的ABCMeta对象参数必须是映射,而不是GridSearchCV

时间:2016-01-25 19:06:57

标签: python scikit-learn graphviz decision-tree

我使用GridSearchCV开发了一个决策树。当我尝试使用导出graphviz导出树时,我得到一个我不明白的错误。我根本不使用ABCMeta对象。

from sklearn import tree

pipeline = Pipeline([
    ('vect', tfidf_vectorizer),  
    ('clf', DecisionTreeClassifier()),  
])
grid_dt = GridSearchCV(
    pipeline,  
    param_grid=params_dt,  # parameters to tune
    # refit=True,  n_jobs=-1,  
    scoring='accuracy', cv=10
)

dt_fit = grid_dt.fit(X_train, y_train)

with open('dtvis.dot', 'w') as file:
    tree.export_graphviz(dt_fit , out_file = "dtvis.dot", feature_names=terms, class_names=True)
file.close()

import subprocess
subprocess.call(['dot', '-Tpdf', 'dtvis.dot', '-o' 'dtvis.pdf'])

回溯:

Traceback (most recent call last):
  File "../dt.py", line 241, in <module>
    dt_grid = DecisionTreeClassifier(**dt_fit)
TypeError: ABCMeta object argument after ** must be a mapping, not GridSearchCV

New Traceback:

Traceback (most recent call last):
  File ".../dt.py", line 245, in <module>
    export_graphviz(dt_fit, out_file = "dtvis.dot", feature_names=terms, class_names=True) 
  .../export.py", line 403, in export_graphviz
    recurse(decision_tree.tree_, 0, criterion=decision_tree.criterion)
AttributeError: 'GridSearchCV' object has no attribute 'tree_'

这可能是罪魁祸首(tree.export_graphviz):tree.export_graphviz()与export_graphviz()?当它工作时,clf是tree.DecisionTreeClassifier和tree.export_graphviz。我在两行中尝试使用和不使用这些前缀但没有成功。 任何建议或想法都将受到赞赏!

1 个答案:

答案 0 :(得分:2)

尝试在dt_fit.best_estimator_上执行graphviz调用:

tree.export_graphviz(dt_fit.best_estimator_ , out_file = "dtvis.dot", feature_names=terms, class_names=True)

dt_fit是一个GridSearchCV对象,可以包装任何类型的模型,而不仅仅是树,因此不能将其绘制为树。要将其绘制为树,您需要获得GridSearchCV找到的“真实”底层模型,这是best_estimator_给出的。