github page 上有大量关于 scikit-learn 中决策树的讨论。 this SO question 和 scikit-learn documentation page 上有答案,它们提供了帮助您入门的框架。通过所有链接,这里有一些功能允许用户以可概括的方式解决问题。这些功能可以很容易地修改,因为我不知道您是指所有叶子还是单独的每个叶子。我的做法是后者。
第一个函数使用apply 作为查找叶节点索引的廉价方法。没有必要实现您的要求,但我将其包括在内是为了方便,因为您提到您想要调查叶节点并且叶节点索引可能是未知的先验。
def find_leaves(X, clf):
"""A cheap function to find leaves of a DecisionTreeClassifier
clf must be a fitted DecisionTreeClassifier
"""
return set(clf.apply(X))
示例结果:
find_leaves(X, alg)
{1, 7, 8, 9, 10, 11, 12}
以下函数将返回满足node 和feature 条件的值数组,其中node 是树中要为其取值的节点的索引,feature 是列X 中您想要的(或功能)。
def node_feature_values(X, clf, node=0, feature=0, require_leaf=False):
"""this function will return an array of values
from the input array X. Array values will be limited to
1. samples that passed through <node>
2. and from the feature <feature>.
clf must be a fitted DecisionTreeClassifier
"""
leaf_ids = find_leaves(X, clf)
if (require_leaf and
node not in leaf_ids):
print("<require_leaf> is set, "
"select one of these nodes:\n{}".format(leaf_ids))
return
# a sparse array that contains node assignment by sample
node_indicator = clf.decision_path(X)
node_array = node_indicator.toarray()
# which samples at least passed through the node
samples_in_node_mask = node_array[:,node]==1
return X[samples_in_node_mask, feature]
应用于示例:
values_arr = node_feature_values(X, alg, node=12, feature=0, require_leaf=True)
array([6.3, 5.8, 7.1, 6.3, 6.5, 7.6, 7.3, 6.7, 7.2, 6.5, 6.4, 6.8, 5.7,
5.8, 6.4, 6.5, 7.7, 7.7, 6.9, 5.6, 7.7, 6.3, 6.7, 7.2, 6.1, 6.4,
7.4, 7.9, 6.4, 7.7, 6.3, 6.4, 6.9, 6.7, 6.9, 5.8, 6.8, 6.7, 6.7,
6.3, 6.5, 6.2, 5.9])
现在,用户可以对给定特征的样本子集执行任何所需的数学运算。
即树的叶子中“X”数据数组中特征 1 的总和。
print("There are {} total samples in this node, "
"{}% of the total".format(len(values_arr), len(values_arr) / float(len(X))*100))
print("Feature Sum: {}".format(values_arr.sum()))
There are 43 total samples in this node,28.666666666666668% of the total
Feature Sum: 286.69999999999993
更新
重新阅读问题后,这是我可以快速组合的唯一解决方案,不涉及修改 export.py 的 scikit 源代码。下面的代码仍然依赖于先前定义的函数。此代码通过pydot 和networkx 修改dotstring。
# Load the data from `dot_data` variable, which you defined.
import pydot
dot_graph = pydot.graph_from_dot_data(dot_data)[0]
import networkx as nx
MG = nx.nx_pydot.from_pydot(dot_graph)
# Select a `feature` and edit the `dot` string in `networkx`.
feature = 0
for n in find_leaves(X, alg):
nfv = node_feature_values(X, alg, node=n, feature=feature)
MG.node[str(n)]['label'] = MG.node[str(n)]['label'] + "\nfeature_{} sum: {}".format(feature, nfv.sum())
# Export the `networkx` graph then plot using `graphviz.Source()`
new_dot_data = nx.nx_pydot.to_pydot(MG)
graph = graphviz.Source(new_dot_data.create_dot())
graph
请注意,对于特征 0,所有叶子都具有来自 X 的值的总和。
我认为完成您所要求的最佳方法是修改 tree.py 和/或 export.py 以原生支持此功能。