获取叶子节点(随机森林)的决策路径中的所有功能

时间:2017-04-12 05:53:20

标签: python-3.x scikit-learn random-forest decision-tree

我只使用2个决策树在虹膜数据集上有一个简单的随机森林分类器的示例代码。这段代码最好在jupyter笔记本中运行。

# Setup
%matplotlib inline
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.cross_validation import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import confusion_matrix
import numpy as np
# Set seed for reproducibility
np.random.seed(1015)

# Load the iris data
iris = load_iris()

# Create the train-test datasets
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target)

np.random.seed(1039)

# Just fit a simple random forest classifier with 2 decision trees
rf = RandomForestClassifier(n_estimators = 2)
rf.fit(X = X_train, y = y_train)

# Define a function to draw the decision trees in IPython
# Adapted from: http://scikit-learn.org/stable/modules/tree.html
from IPython.display import display, Image
import pydotplus

# Now plot the trees individually
for dtree in rf.estimators_:
    dot_data = tree.export_graphviz(dtree
                                    , out_file = None
                                    , filled   = True
                                    , rounded  = True
                                    , special_characters = True)  
    graph = pydotplus.graph_from_dot_data(dot_data)  
    img = Image(graph.create_png())
    display(img)
    draw_tree(inp_tree = dtree)
    #print(dtree.tree_.feature)

第一棵树的输出是:

enter image description here

可以看出,第一个决策有 8个叶子节点,第二个决策树(未显示)有 6个叶子节点

如何提取一个简单的numpy数组,其中包含每个决策树的信息,以及树中的每个叶节点:

  • 该叶节点的分类结果(例如最常见的类预测)
  • 在同一叶节点的决策路径中使用的所有功能(布尔值)?

在上面的示例中,我们将:

  • 2棵树 - {0, 1}
  • 对于树{0},我们有8个叶节点已编入索引{0, 1, ..., 7}
  • 对于树{1},我们有6个叶节点已编入索引{0, 1, ..., 5}
  • 对于每棵树中的每个叶节点,我们有一个单个最常见的预测类,即 iris 数据集的{0, 1, 2}
  • 对于每个叶节点,我们有一组用于制作该树的4个特征的布尔值。如果在叶子节点的决策路径中使用一次或多次 4个特征中的一个,我们将其视为True否则为False,如果它从未用于叶子节点的决策路径。

任何帮助将此numpy数组调整为上述代码(循环)的帮助表示赞赏。

由于

1 个答案:

答案 0 :(得分:1)

类似于这里的问题:how extraction decision rules of random forest in python

您可以使用提供的代码段@jonnor(我也对它进行了修改):

import numpy
from sklearn.model_selection import train_test_split
from sklearn import metrics, datasets, ensemble

def print_decision_rules(rf):

    for tree_idx, est in enumerate(rf.estimators_):
        tree = est.tree_
        assert tree.value.shape[1] == 1 # no support for multi-output

        print('TREE: {}'.format(tree_idx))

        iterator = enumerate(zip(tree.children_left, tree.children_right, tree.feature, tree.threshold, tree.value))
        for node_idx, data in iterator:
            left, right, feature, th, value = data

            # left: index of left child (if any)
            # right: index of right child (if any)
            # feature: index of the feature to check
            # th: the threshold to compare against
            # value: values associated with classes            

            # for classifier, value is 0 except the index of the class to return
            class_idx = numpy.argmax(value[0])

            if left == -1 and right == -1:
                print('{} LEAF: return class={}'.format(node_idx, class_idx))
            else:
                print('{} NODE: if feature[{}] < {} then next={} else next={}'.format(node_idx, feature, th, left, right))    


digits = datasets.load_digits()
Xtrain, Xtest, ytrain, ytest = train_test_split(digits.data, digits.target)
estimator = ensemble.RandomForestClassifier(n_estimators=3, max_depth=2)
estimator.fit(Xtrain, ytrain)

另一种可视化方法:

要可视化决策路径,您可以使用dtreeviz中的库https://explained.ai/decision-tree-viz/index.html

它们具有出色的可视化效果,例如: enter image description here

来源https://explained.ai/decision-tree-viz/images/samples/sweets-TD-3-X.svg

请查看其shadowDecisionTree实现,以获取有关决策路径的更多信息。在https://explained.ai/decision-tree-viz/index.html中,他们还提供了一个示例

shadow_tree = ShadowDecTree(tree_model, X_train, y_train, feature_names, class_names)

然后,您可以使用类似get_leaf_sample_counts方法的方法。