在 Python 中使用 DecisonTreeclassifer() 构建决策树时遇到错误

我使用以下代码来构建决策树。在通过网格搜索获得构建决策树的最佳标准后,当我使用 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'])

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注