如何获取决策树每片叶子节点下的样本?

我已经使用数据集训练了一个决策树。现在我想查看哪些样本落在了树的哪些叶子节点下。

我想要的是红色圈起来的样本。

enter image description here

我使用的是Python的Sklearn决策树实现。


回答:

如果你只想要每个样本对应的叶子节点,你可以直接使用

clf.apply(iris.data)

array([ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 14, 5, 5, 5, 5, 5, 5, 10, 5, 5, 5, 5, 5, 10, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 16, 16, 16, 16, 16, 16, 6, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 8, 16, 16, 16, 16, 16, 16, 15, 16, 16, 11, 16, 16, 16, 8, 8, 16, 16, 16, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16])

如果你想获取每个节点的所有样本,你可以计算所有决策路径,使用

dec_paths = clf.decision_path(iris.data)

然后遍历决策路径,将它们转换为数组,使用toarray()并检查它们是否属于某个节点。所有内容都存储在一个defaultdict中,键是节点编号,值是样本编号。

for d, dec in enumerate(dec_paths):    for i in range(clf.tree_.node_count):        if dec.toarray()[0][i] == 1:            samples[i].append(d)

完整代码

import sklearn.datasetsimport sklearn.treeimport collectionsclf = sklearn.tree.DecisionTreeClassifier(random_state=42)iris = sklearn.datasets.load_iris()clf = clf.fit(iris.data, iris.target)samples = collections.defaultdict(list)dec_paths = clf.decision_path(iris.data)for d, dec in enumerate(dec_paths):    for i in range(clf.tree_.node_count):        if dec.toarray()[0][i] == 1:            samples[i].append(d) 

输出

print(samples[13])

[70, 126, 138]

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中创建了一个多类分类项目。该项目可以对…

发表回复

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