DecisonTreeclassifer () в Python - ошибка при попытке построить дерево - PullRequest
0 голосов
/ 21 января 2020

Я использую следующий код для построения дерева решений. После получения лучшего Криетриона, чтобы построить дерево, используя gridsearch. Когда я использую 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 :tree
clf = DecisionTreeClassifier()

#initiate decison tree classifier with the randomised search
clf_cv=RandomizedSearchCV(clf,param_dist,cv=5)

# Train Decision Tree Classifer
clf_fit=clf_cv.fit(X_train,y_train)

#Print the tuned paramenters and score
print("Tuned decision tree parameters:{}".format(clf_cv.best_params_))


#Predict the response for test dataset
y_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 matrix
from sklearn.metrics import confusion_matrix
cm= confusion_matrix(y_test,y_pred)

from sklearn.externals.six import StringIO  
from IPython.display import Image  
from sklearn.tree import export_graphviz
import pydotplus
dot_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())```

1 Ответ

1 голос
/ 21 января 2020

Вам нужно позвонить clf_fit.best_estimator_, чтобы получить лучшую оценку, которая имеет лучший CV. Это будет экземпляр 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'])
...