我只使用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 leaf nodes ,第二个决策树(未显示)有 6 leaf nodes

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

  • 该叶节点的分类结果(例如,它预测的 most frequent 类)

  • 在同一叶节点的决策路径中使用的所有功能(布尔值)?

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

  • 2棵树 - {0, 1}

  • for tree {0} 我们有8个叶子节点索引 {0, 1, ..., 7}

  • for tree {1} 我们有6个叶子节点索引 {0, 1, ..., 5}

  • 对于每个树中的每个叶节点,我们有一个 single most frequent predicted class ,即 {0, 1, 2} 用于虹膜数据集

  • 对于每个叶节点,我们有一组用于制作该树的4个特征的布尔值 . 这里,如果4个特征中的一个在叶子节点的决策路径中被使用了一次或多次,我们将其视为 True 否则 False 如果它从未在叶子节点的决策路径中使用 .

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

谢谢