【发布时间】:2018-01-06 00:19:27
【问题描述】:
【问题讨论】:
-
左上叶是故意漏掉的吗?
标签: python machine-learning scikit-learn decision-tree
【问题讨论】:
标签: python machine-learning scikit-learn decision-tree
如果你只想要每个样本的叶子,你可以使用
clf.apply(iris.data)
数组([ 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.datasets
import sklearn.tree
import collections
clf = 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]
【讨论】:
13是节点号
clf.decision_path(my_test_samples),你应该得到这些样本的决策路径。