如何 return 在 sklearn 中由 DecisionTreeClassifier 创建的决策树中使用的特征

how to return the features that used in decision tree that created by DecisionTreeClassifier in sklearn

我想通过 CART 和 C4.5 决策树对我的数据集进行特征选择。以这种方式将决策树应用于数据集,然后提取决策树算法用于创建树的特征。所以我需要 return 在创建的树中使用的功能。我在 sklearn.tree 模块中使用“DecisionTreeClassifier”。我需要一种方法或函数来给我 (return) 创建树中使用的功能!!将此功能用作主要调制算法中更重要的功能。

您可以解决类似以下问题:

我假设你有火车 (x_train, y_train) 和测试 (x_test, y_test) 集。

from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score
from sklearn.metrics import f1_score

tree_clf1 = DecisionTreeClassifier().fit(x_train, y_train)

y_pred = tree_clf1.predict(x_test)

print(confusion_matrix(y_test, y_pred))
print("\n\nAccuracy:{:,.2f}%".format(accuracy_score(y_test, y_pred)*100))
print("Precision:{:,.2f}%".format(precision_score(y_test, y_pred)*100))
print("Recall:{:,.2f}%".format(recall_score(y_test, y_pred)*100))
print("F1-Score:{:,.2f}%".format(f1_score(y_test, y_pred)*100))

feature_importances = DataFrame(tree_clf1.feature_importances_,
                                index = x_train.columns,
                                columns['importance']).sort_values('importance', 
                                                                    ascending=False)

print(feature_importances)

下面是一个示例输出,显示了哪些特征对您的分类很重要。