决策树 – 查找常数预测在树遍历过程中如何变化

假设我有以下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]))

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注