Pra*_*nka 12 python decision-tree pygraphviz scikit-learn
我目前正在使用以下代码查看决策树.有没有办法我们可以将一些计算字段输出为输出?
例如,是有可能在树的叶子在每个节点显示输入属性的总和,特征1的从"X"的数据数组,即总和.
from sklearn import datasets
iris = datasets.load_iris()
X = iris.data[:]
y = iris.target
#%%
from sklearn.tree import DecisionTreeClassifier
alg=DecisionTreeClassifier( max_depth=5,min_samples_leaf=2, max_leaf_nodes = 10)
alg.fit(X,y)
#%%
## View tree
import graphviz
from sklearn import tree
dot_data = tree.export_graphviz(alg,out_file=None, node_ids = True, proportion = True, class_names = True, filled = True, rounded = True)
graph = graphviz.Source(dot_data)
graph
Run Code Online (Sandbox Code Playgroud)
在github页面上有关于scikit-learn的决策树的讨论很多.这个SO问题和这个scikit-learn文档页面都有答案,它提供了帮助您入门的框架.通过所有链接,这里有一些功能允许用户以一般化的方式解决问题.这些功能很容易修改,因为我不知道你是指所有的叶子还是每片叶子.我的方法是后者.
第一个函数使用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))
Run Code Online (Sandbox Code Playgroud)
结果示例:
find_leaves(X, alg)
{1, 7, 8, 9, 10, 11, 12}
Run Code Online (Sandbox Code Playgroud)
以下函数将返回满足条件值的数组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]
Run Code Online (Sandbox Code Playgroud)
应用于示例:
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])
Run Code Online (Sandbox Code Playgroud)
现在,用户可以对给定特征的样本子集执行所需的任何数学运算.
即树的叶子中'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
Run Code Online (Sandbox Code Playgroud)
更新
重新阅读的问题后,这是唯一的解决方案,我可以快速地放在一起,不涉及修改scikit源代码export.py.下面的代码仍然依赖于先前定义的函数.此代码dot通过pydot和networkx修改字符串.
# 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
Run Code Online (Sandbox Code Playgroud)
请注意,所有叶子都具有来自X特征的值的总和0.我认为,实现您所要求的最佳方法是修改tree.py和/或export.py本地支持此功能.
| 归档时间: |
|
| 查看次数: |
1200 次 |
| 最近记录: |