【发布时间】:2019-02-21 21:09:55
【问题描述】:
我一直在尝试分析我在sklearn 中训练的DecisionTreeRegressor。我发现http://scikit-learn.org/stable/auto_examples/tree/plot_unveil_tree_structure.html 在确定拆分树中每个分支的属性时很有用,特别是这段代码 sn-p:
n_nodes = estimator.tree_.node_count
children_left = estimator.tree_.children_left
children_right = estimator.tree_.children_right
feature = estimator.tree_.feature
threshold = estimator.tree_.threshold
# The tree structure can be traversed to compute various properties such
# as the depth of each node and whether or not it is a leaf.
node_depth = np.zeros(shape=n_nodes, dtype=np.int64)
is_leaves = np.zeros(shape=n_nodes, dtype=bool)
stack = [(0, -1)] # seed is the root node id and its parent depth
while len(stack) > 0:
node_id, parent_depth = stack.pop()
node_depth[node_id] = parent_depth + 1
# If we have a test node
if (children_left[node_id] != children_right[node_id]):
stack.append((children_left[node_id], parent_depth + 1))
stack.append((children_right[node_id], parent_depth + 1))
else:
is_leaves[node_id] = True
print("The binary tree structure has %s nodes and has "
"the following tree structure:"
% n_nodes)
for i in range(n_nodes):
if is_leaves[i]:
print("%snode=%s leaf node." % (node_depth[i] * "\t", i))
else:
print("%snode=%s test node: go to node %s if X[:, %s] <= %s else to "
"node %s."
% (node_depth[i] * "\t",
i,
children_left[i],
feature[i],
threshold[i],
children_right[i],
))
但是,这并没有告诉我每个叶节点的 值。如果上面打印出如下所示的内容:
The binary tree structure has 7 nodes and has the following tree structure:
node=0 test node: go to node 1 if X[:, 2] <= 1.00764083862 else to node 4.
node=1 test node: go to node 2 if X[:, 2] <= 0.974808812141 else to node 3.
node=2 leaf node.
node=3 leaf node.
node=4 test node: go to node 5 if X[:, 0] <= -2.90554761887 else to node 6.
node=5 leaf node.
node=6 leaf node.
例如我怎么知道节点2代表的值?
【问题讨论】:
-
你好@desertnaut 进一步的问题。如何计算由决策树训练的叶子?例如,我如何获得其他统计信息,例如
len(node3_leaf_values)、stddev(node3_leaf_values)或只是node3_leaf_values的列表? -
请打开一个包含详细信息的新问题(它是免费的!),如有必要,请链接到这个问题,但请注意,我不能保证我能够查看它(顺便说一句,赞成欢迎在下面回答您之前的问题)...
标签: python machine-learning scikit-learn decision-tree