“DecisionTreeClassifier”对象没有属性“importances_”

数据挖掘 Python 预测建模 特征选择 决策树 估计者
2021-10-11 03:56:26

我有这段代码是为了可视化每个模型的最重要特征:

dtc = DecisionTreeClassifier(min_samples_split=7, random_state=111)
rfc = RandomForestClassifier(n_estimators=31, random_state=111)
trained_model = dtc.fit(features_train, labels_train)
trained_model.fit(features_train, labels_train)
predictions = trained_model.predict(features_test)
importances = trained_model.feature_importances_
    std = np.std([trained_model.feature_importances_ for trained_model in 
 trained_model.estimators_], axis=0)
 indices = np.argsort(importances)[::-1]
    for f in range(features_train.shape[1]):
        print("%d. feature %d (%f)" % (f + 1, indices[f], importances[indices[f]]))
        plt.figure()
        plt.title("Feature importances")
        plt.bar(range(features_train.shape[1]), importances[indices], color="r", yerr=std[indices], align="center")
        plt.xticks(range(features_train.shape[1]), indices)
        plt.xlim([-1, features_train.shape[1]])
        plt.show()

使用 RandomForestClassifier 这段代码运行良好,但是当我使用 Decison Trees 分类器尝试它时,我收到以下错误:

std = np.std([trained_model.feature_importances_ for trained_model in trained_model.estimators_], axis=0)

builtins.AttributeError: 'DecisionTreeClassifier' object has no attribute 'estimators_'

我应该使用哪个属性来查看每个模型的最重要特征?

1个回答

结帐此链接

可视化树本身

from sklearn.tree import export_graphviz
import graphviz

export_graphviz(tree, out_file="mytree.dot")
with open("mytree.dot") as f:
    dot_graph = f.read()
graphviz.Source(dot_graph)

或者

from sklearn.tree import convert_to_graphviz
convert_to_graphviz(tree)

或者

from sklearn.tree import convert_to_graphviz
import graphviz

graphviz.Source(export_graphviz(tree))

您可以获得的可视化将是整棵树本身。 射频

显示特征重要性

from sklearn.tree import DecisionTreeClassifier
classifier = DecisionTreeClassifier()
classifier.fit(features, labels)
for name, importance in zip(features.columns, classifier.feature_importances_):
    print(name, importance)
    ## Now You Can Do Whatever You Want(plot them using a Barplot etc)