简体   繁体   English

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

[英]Decision path for a Random Forest Classifier

Here is my code to run it in your environment, I am using the RandomForestClassifier and I am trying to figure out the decision_path for a selected sample in the RandomForestClassifier .这里是我的代码在您的环境中运行它,我现在用的是RandomForestClassifier ,我试图找出decision_path在选定的样品RandomForestClassifier

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)

The furthest I got is this:我得到的最远的是这样的:

#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)

But the output doesn't make much sense:但输出没有多大意义:

(<1x7046 sparse matrix of type '<class 'numpy.int64'>' with 486 stored elements in Compressed Sparse Row format>, 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)) (<1x7046 稀疏矩阵,类型为 '<class 'numpy.int64'>',以压缩稀疏行格式存储 486 个元素>, array([ 0, 133, 282, 415, 588, 761, 910, 1041, 11092, 1 ,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

I am trying to figure out the decision path for a particle sample in the dataframe.我试图找出数据帧中粒子样本的决策路径。 Can anyone tell me how to do that?谁能告诉我怎么做?

The idea is to have something like this .这个想法是有一些像这样

RandomForestClassifier.decision_path method returns a tuple of (indicator, n_nodes_ptr) . RandomForestClassifier.decision_path方法返回(indicator, n_nodes_ptr)tuple see the documentation : here查看文档: 这里

So your variable node_indicator is a tuple and not what you think it is.所以你的变量node_indicator是一个元组,而不是你认为的那样。 A tuple object has no attribute 'indices' that's why you get the error when you do :元组对象没有属性“索引”,这就是为什么您在执行以下操作时会收到错误:

node_index = node_indicator.indices[node_indicator.indptr[sample_id]:
                                    node_indicator.indptr[sample_id + 1]]

try :尝试:

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

You can also plot the decision tree of each tree of the forest for a single sample id :您还可以为单个样本 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]))

Note that in your case, you have 50 estimators so it might be a bit boring to read.请注意,在您的情况下,您有 50 个估算器,因此阅读起来可能有点无聊。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM