我使用以下代码来构建决策树。在通过网格搜索获得构建决策树的最佳标准后,当我使用 graphviz 来绘制决策树时,遇到了以下错误
Error--- File "C:\Users\lalitha.sundar\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\tree\export.py", line 396, in export_graphviz check_is_fitted(decision_tree, 'tree_') File "C:\Users\lalitha.sundar\AppData\Local\Continuum\anaconda3\lib\site-packages\sklearn\utils\validation.py", line 951, in check_is_fitted raise NotFittedError(msg % {'name': type(estimator).__name__})NotFittedError: This RandomizedSearchCV instance is not fitted yet. Call 'fit' with appropriate arguments before using this method.
param_dist={"max_depth":[3,None], "min_samples_leaf": randint(1,9), "criterion":["gini","entropy"]}#initiate decison tree classifier :treeclf = DecisionTreeClassifier()#initiate decison tree classifier with the randomised searchclf_cv=RandomizedSearchCV(clf,param_dist,cv=5)# Train Decision Tree Classiferclf_fit=clf_cv.fit(X_train,y_train)#Print the tuned paramenters and scoreprint("Tuned decision tree parameters:{}".format(clf_cv.best_params_))#Predict the response for test datasety_pred = clf_cv.predict(X_test)# Model Accuracy, how often is the classifier correct?print("Accuracy:",metrics.accuracy_score(y_test, y_pred))##generating confusion matrixfrom sklearn.metrics import confusion_matrixcm= confusion_matrix(y_test,y_pred)from sklearn.externals.six import StringIO from IPython.display import Image from sklearn.tree import export_graphvizimport pydotplusdot_data = StringIO()export_graphviz(clf_fit, out_file=dot_data, filled=True, rounded=True, special_characters=True, feature_names = feature_cols,class_names=['0','1'])graph = pydotplus.graph_from_dot_data(dot_data.getvalue()) graph.write_png('diabetes.png')Image(graph.create_png())```
回答:
你需要调用 clf_fit.best_estimator_
来获取具有最佳交叉验证得分的最佳估计器。这将是一个已经拟合好的 DecisionTreeClassifier
实例。
export_graphviz(clf_fit.best_estimator_, out_file=dot_data, filled=True, rounded=True, special_characters=True, feature_names = feature_cols,class_names=['0','1'])