假设我有以下DecisionTreeClassifier
模型:
from sklearn.tree import DecisionTreeClassifierfrom sklearn.datasets import load_breast_cancerbunch = load_breast_cancer()X, y = bunch.data, bunch.targetmodel = DecisionTreeClassifier(random_state=100)model.fit(X, y)
我想遍历这棵树中的每个节点(包括叶节点和决策节点),并确定预测值在遍历过程中如何变化。基本上,我希望能够了解,对于给定的样本,最终的预测(由.predict
返回)是如何确定的。比如,样本最终可能被预测为1
,但在遍历了四个节点后,在每个节点上的“常数”(scikit文档中使用的术语)预测值从1
变为0
,再变为0
,最后又变为1
。
从model.tree_.value
中获取这些信息的方法并不明显,其描述如下:
| value : array of double, shape [node_count, n_outputs, max_n_classes] | Contains the constant prediction value of each node.
在该模型的情况下,看起来像这样:
>>> model.tree_.value.shape(43, 1, 2)>>> model.tree_.valuearray([[[212., 357.]], [[ 33., 346.]], [[ 5., 328.]], [[ 4., 328.]], [[ 2., 317.]], [[ 1., 6.]], [[ 1., 0.]], [[ 0., 6.]], [[ 1., 311.]], [[ 0., 292.]], [[ 1., 19.]], [[ 1., 0.]], [[ 0., 19.]],
有谁知道我如何实现这个目标吗?对于上面43个节点中的每一个,其类别预测是否只是每个列表的argmax?所以从上到下是1, 1, 1, 1, 1, 1, 0, 0, …?
回答:
一种解决方案可能是直接遍历树中的决策路径。你可以改编这个解决方案,它将整个决策树打印为if语句。这里是快速改编以解释一个实例的代码:
def tree_path(instance, values, left, right, threshold, features, node, depth): spacer = ' ' * depth if (threshold[node] != _tree.TREE_UNDEFINED): if instance[features[node]] <= threshold[node]: path = f'{spacer}{features[node]} ({round(instance[features[node]], 2)}) <= {round(threshold[node], 2)}' next_node = left[node] else: path = f'{spacer}{features[node]} ({round(instance[features[node]], 2)}) > {round(threshold[node], 2)}' next_node = right[node] return path + '\n' + tree_path(instance, values, left, right, threshold, features, next_node, depth+1) else: target = values[node] for i, v in zip(np.nonzero(target)[1], target[np.nonzero(target)]): target_count = int(v) return spacer + "==> " + str(round(target[0][0], 2)) + \ " ( " + str(target_count) + " examples )"def get_path_code(tree, feature_names, instance): left = tree.tree_.children_left right = tree.tree_.children_right threshold = tree.tree_.threshold features = [feature_names[i] for i in tree.tree_.feature] values = tree.tree_.value return tree_path(instance, values, left, right, threshold, features, 0, 0)# print the decision path of the first intance of a panda dataframe dfprint(get_path_code(tree, df.columns, df.iloc[0]))