随机森林分类器的决策路径

3

这是我的代码,可以在你的环境中运行。我正在使用RandomForestClassifier,并尝试找出RandomForestClassifier中选择样本的decision_path

import numpy as np
import pandas as pd
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier

X, y = make_classification(n_samples=1000,
                           n_features=6,
                           n_informative=3,
                           n_classes=2,
                           random_state=0,
                           shuffle=False)

# Creating a dataFrame
df = pd.DataFrame({'Feature 1':X[:,0],
                                  'Feature 2':X[:,1],
                                  'Feature 3':X[:,2],
                                  'Feature 4':X[:,3],
                                  'Feature 5':X[:,4],
                                  'Feature 6':X[:,5],
                                  'Class':y})


y_train = df['Class']
X_train = df.drop('Class',axis = 1)

rf = RandomForestClassifier(n_estimators=50,
                               random_state=0)

rf.fit(X_train, y_train)

我最终达成的是这个:
#Extracting the decision path for instance i = 12
i_data = X_train.iloc[12].values.reshape(1,-1)
d_path = rf.decision_path(i_data)

print(d_path)

但输出的结果并不是很清晰:

(<1x7046 压缩稀疏行矩阵,类型为 '<class 'numpy.int64'>', 其中有486个元素存储在Compressed Sparse Row格式中>, array([ 0, 133, 282, 415, 588, 761, 910, 1041, 1182, 1309, 1432, 1569, 1728, 1869, 2000, 2143, 2284, 2419, 2572, 2711, 2856, 2987, 3128, 3261, 3430, 3549, 3704, 3839, 3980, 4127, 4258, 4389, 4534, 4671, 4808, 4947, 5088, 5247, 5378, 5517, 5640, 5769, 5956, 6079, 6226, 6385, 6524, 6655, 6780, 6925, 7046], dtype=int32))

我想要找到数据框中粒子样本的决策路径。有没有人能告诉我该如何操作呢?

我的想法是得到类似于 这个 的图表。

1个回答

4
RandomForestClassifier.decision_path 方法返回一个 (indicator, n_nodes_ptr) 的元组。 请参阅文档: 这里 因此,您的变量 node_indicator 是一个元组,而不是您想象的那样。 元组对象没有属性 'indices',这就是为什么当您执行以下操作时会出现错误:
node_index = node_indicator.indices[node_indicator.indptr[sample_id]:
                                    node_indicator.indptr[sample_id + 1]]

尝试:

(node_indicator, _) = rf.decision_path(X_train)

您可以为森林中每个树的单个样本ID绘制决策树:
X_train = X_train.values

sample_id = 0

for j, tree in enumerate(rf.estimators_):

    n_nodes = tree.tree_.node_count
    children_left = tree.tree_.children_left
    children_right = tree.tree_.children_right
    feature = tree.tree_.feature
    threshold = tree.tree_.threshold

    print("Decision path for DecisionTree {0}".format(j))
    node_indicator = tree.decision_path(X_train)
    leave_id = tree.apply(X_train)
    node_index = node_indicator.indices[node_indicator.indptr[sample_id]:
                                        node_indicator.indptr[sample_id + 1]]



    print('Rules used to predict sample %s: ' % sample_id)
    for node_id in node_index:
        if leave_id[sample_id] != node_id:
            continue

        if (X_train[sample_id, feature[node_id]] <= threshold[node_id]):
            threshold_sign = "<="
        else:
            threshold_sign = ">"

        print("decision id node %s : (X_train[%s, %s] (= %s) %s %s)"
              % (node_id,
                 sample_id,
                 feature[node_id],
                 X_train[sample_id, feature[node_id]],
                 threshold_sign,
                 threshold[node_id]))

请注意,根据您的情况,您有50个估算器,因此阅读可能会有些乏味。

随机森林的决策路径是否可以找到? - user9238790
是的,在幕后,它将森林中每个树的决策路径结合起来。 - arthur
问题在于我无法弄清楚如何访问样本ID中的数据框。 - user9238790
@arther,另外,我们还没有定义功能或阈值,因此你的代码无法运行。请直接删除答案。 - user9238790
我并没有说我的代码可以工作,我只是说它解决了你最初的错误。问题在于你从这里应用了一段关于DecisionTreeClassifier的代码:http://scikit-learn.org/stable/auto_examples/tree/plot_unveil_tree_structure.html,而你却没有做任何修改就将其应用到了RandomForestClassifier上!在我解决了问题之后,你需要重新审查代码的以下部分以使其能够工作。 - arthur
让我们在聊天中继续这个讨论。点击此处进入聊天室 - arthur

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接