我已经使用数据集训练了一个决策树。现在我想查看哪些样本落在了树的哪些叶子节点下。
我想要的是红色圈起来的样本。
我使用的是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]