【问题标题】:how to return the features that used in decision tree that created by DecisionTreeClassifier in sklearn如何返回在 sklearn 中由 DecisionTreeClassifier 创建的决策树中使用的特征
【发布时间】:2020-10-30 07:50:10
【问题描述】:

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

【问题讨论】:

    标签: scikit-learn decision-tree feature-selection


    【解决方案1】:

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

    我假设你有训练 (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)
    

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

    【讨论】:

      猜你喜欢
      • 2021-06-07
      • 2021-07-25
      • 2019-03-04
      • 2016-12-20
      • 2017-10-11
      • 2021-10-20
      • 2018-01-01
      • 2018-10-15
      相关资源
      最近更新 更多