【问题标题】:Total Gini impurity or entropy gain for a scikit-learn decision treescikit-learn 决策树的总基尼杂质或熵增益
【发布时间】:2022-11-05 07:26:13
【问题描述】:

如何在 scikit-learn 中的经过训练的决策树上获得总加权 Gini 杂质(或熵)?例如,以下关于泰坦尼克数据集的代码,

import pandas as pd
import matplotlib.pyplot as plt
from sklearn import tree
df_titanic = pd.read_csv('titanic_data.csv')    # a popular dataset
feat_list = ['SibSp','Pclass']  # number of siblings and spouses aboard; passenger class (1st,2nd,3rd)
clf = tree.DecisionTreeClassifier()
clf = clf.fit(df_titanic.loc[:,feat_list],df_titanic['Survived'])
fig = plt.figure(figsize=(10,10))
tree.plot_tree(clf,feature_names=feat_list,class_names=['NS','S'])
fig.show()

产生一棵树,其叶子的基尼杂质值和样本大小(无特定顺序)(0.378,71),(0.32,5),(0.5,8),......我对加权和感兴趣,0.378( 71/891) + 0.32(5/891) + 0.5(8/891) + ... 其中 891 是样本总数(乘客)。有什么简单的方法可以做到这一点?

我想比较构建树之前和之后的总基尼杂质(或熵)(如在 Provost 和 Fawcett 中),但是在研究了一些文档之后,似乎没有直接的树属性或方法产生这个信息。

【问题讨论】:

    标签: python scikit-learn tree entropy


    【解决方案1】:

    我最终做了什么——继续问题发布中的示例:

    # determine starting gini impurity (without any decision tree)
    surv_clss = df_titanic['Survived'][:]   # 0=did not survive; 1=survived
    p_0 = sum((surv_clss==0))/len(surv_clss)
    gini_start = 1-(p_0**2+(1-p_0)**2)
    print("impurity before: %s" % gini_start)
    
    # get leaf node indices
    leaf_nodes_by_sample = clf.apply(df_titanic.loc[:,feat_list]) # .apply gets the
    # leaf node each sample belongs to
    leaf_nodes = np.unique(leaf_nodes_per_sample)
    
    # determine total gini impurity of decision tree (weighted average)
    tot_imp = 0.0
    num_sam = len(df_titanic.index)
    for node in leaf_nodes:
        nd_ct = clf.tree_.n_node_samples[node]  # num samples at 'node'
        tot_imp += (nd_ct/num_sam)*clf.tree_.impurity[node] # gini impurity at 'node'
    
    print("average weighted impurity after the tree: %s" % tot_imp)
    

    有关导航决策树并获取其属性的文档,请参阅https://scikit-learn.org/stable/auto_examples/tree/plot_unveil_tree_structure.html

    这行得通,但是,我再次认为可能有更简单的方法(?)

    【讨论】:

      猜你喜欢
      • 2016-04-10
      • 2018-10-04
      • 2014-01-07
      • 2016-06-23
      • 2017-02-23
      • 2020-04-05
      • 2017-03-26
      相关资源
      最近更新 更多