【发布时间】:2017-09-07 17:58:45
【问题描述】:
我有以下示例代码,用于仅使用 2 个决策树在 iris 数据集上的简单随机森林分类器。此代码最好在 jupyter notebook 中运行。
# 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)
第一棵树的输出是:
可以看出,第一个决策有 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 数组改编为上述代码(循环)的帮助。
谢谢
【问题讨论】:
-
你有没有看过
tree类中的代码,特别是我认为export_graphiz函数的代码是一个很好的起点github.com/scikit-learn/scikit-learn/blob/14031f6/sklearn/tree/… -
当我尝试运行您的代码时,我得到 name 'draw_tree' is not defined 有什么想法吗?
-
@user4687531 当我尝试运行您的代码时,我得到 name 'draw_tree' is not defined 任何想法为什么?
-
决策节点可以在 Python 中访问,参见stackoverflow.com/questions/50600290/…
标签: python-3.x scikit-learn random-forest decision-tree