我有一个已训练的决策树。当我输入一个特征向量进行预测时,我想知道它是从哪个决策路径预测的,或者说新特征落在树的哪个叶子节点下。
我使用的是Python的Sklearn库中的决策树实现。
回答:
可以通过类中的decision_path
方法来访问树中的决策路径。
示例:
from sklearn.ensemble import RandomForestClassifierfrom sklearn.datasets import load_iris import numpy as npdata = load_iris()x = data.datay = data.targetclf = RandomForestClassifier()clf.fit(x,y)clf.decision_path(x)
结果:
(<150x140 sparse matrix of type '<type 'numpy.int64'>'with 5406 stored elements in Compressed Sparse Row format>, array([ 0, 13, 26, 41, 54, 71, 86, 97, 106, 119, 140]))