python - 随机森林分类器决策路径法(scikit)

标签 python scikit-learn random-forest

我已经在 titanic 数据集上实现了一个标准的随机森林分类器,并希望探索 sklearn 在 v0.18 中引入的 decision_path 方法。 ( http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html )

但是,它输出一个我不确定如何理解的稀疏矩阵。任何人都可以就如何最好地将其可视化提出建议吗?

#Training a simplified random forest
estimator = RandomForestClassifier(random_state=0, n_estimators=3, max_depth=3)
estimator.fit(X_train, y_train)

#Extracting the decision path for instance i = 12
i_data = X_test.iloc[12].values.reshape(1,-1)
d_path = rf_best.decision_path(i_data)

print(d_path)

输出:

(<1x3982 sparse matrix of type '' with 598 stored elements in Compressed Sparse Row format>, array([ 0, 45,
98, 149, 190, 233, 258, 309, 360, 401, 430, 461, 512, 541, 580, 623, 668, 711, 760, 803, 852, 889, 932, 981, 1006, 1035, 1074, 1107, 1136, 1165, 1196, 1241, 1262, 1313, 1350, 1385, 1420, 1465, 1518, 1553, 1590, 1625, 1672, 1707, 1744, 1787, 1812, 1863, 1904, 1945, 1982, 2017, 2054, 2097, 2142, 2191, 2228, 2267, 2304, 2343, 2390, 2419, 2456, 2489, 2534, 2583, 2632, 2677, 2714, 2739, 2786, 2833, 2886, 2919, 2960, 2995, 3032, 3073, 3126, 3157, 3194, 3239, 3274, 3313, 3354, 3409, 3458, 3483, 3516, 3539, 3590, 3629, 3660, 3707, 3750, 3777, 3822, 3861, 3898, 3939, 3982], dtype=int32))

如果我没有提供足够的细节,请道歉 - 否则请告诉我。

谢谢!

注意:编辑以简化随机森林(限制深度和 n_trees)

最佳答案

如果您想想象森林中的树木,您可以尝试此处提供的答案:https://stats.stackexchange.com/q/118016

适应你的问题:

from sklearn import tree

...

i_tree = 0
for tree_in_forest in estimator.estimators_:
    with open('tree_' + str(i_tree) + '.dot', 'w') as my_file:
        my_file = tree.export_graphviz(tree_in_forest, out_file = my_file)
    i_tree = i_tree + 1

这将创建 10 个(森林中树木的默认数量)文件,称为 tree_i.dot,i = 0 到 9。您可以为它们中的每一个创建 pdf 文件,在终端上执行(例如):

$ dot -Tpdf tree_0.dot -o tree.pdf

可能有更聪明的方法,如果有人能提供帮助,我很乐意学习它:)

关于python - 随机森林分类器决策路径法(scikit),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42793341/

相关文章:

python - sklearn 逻辑回归 : does it use multiple background threads?

Python 代码在 Eclipse 中出错,但在终端中运行良好

python - Python 上的广义随机森林/因果森林

scikit-learn - 如何缩小词袋模型?

python - 如何在 Django 中对特定用户和特定项目使用 deleteview?

python - 当我的播放器类与我的平台类之一发生碰撞时,如何制作和结束屏幕?

opencv - 有没有比K更快的聚类方法?

python - Pandas:如何通过保留第一个数据帧的信息来合并列上的两个数据帧?

python - 使用 're' 从字符串中提取列表

machine-learning - 交叉验证和随机森林