如何在Python中提取随机森林的决策规则

7

我有一个问题。我听说在R语言中,你可以使用额外的包来提取随机森林实现的决策规则。我试着在Python中搜索类似的内容,但没有成功。如果有任何关于如何实现这一点的帮助,请告诉我。谢谢!

1个回答

9
假设您使用sklearn的RandomForestClassifier,您可以找到各个决策树,如.estimators_。每棵树将决策节点存储为一些NumPy数组,位于tree_下。
以下是一些示例代码,仅按顺序打印每个节点。在典型应用中,人们会跟随子节点遍历。
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)

print_decision_rules(estimator)

示例输出:

TREE: 0
0 NODE: if feature[33] < 2.5 then next=1 else next=4
1 NODE: if feature[38] < 0.5 then next=2 else next=3
2 LEAF: return class=2
3 LEAF: return class=9
4 NODE: if feature[50] < 8.5 then next=5 else next=6
5 LEAF: return class=4
6 LEAF: return class=0
...

emlearn中,我们使用类似的方法将随机森林编译成C代码。


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