python 随机森林可视化

这篇博客展示了如何在Jupyter Notebook中利用Python的sklearn和pydotplus库对随机森林模型进行可视化。首先,使用iris数据集训练了一个最大深度为4的随机森林分类器。然后,通过tree.export_graphviz导出单个决策树,并用pydotplus将其转换为SVG图像进行展示,以帮助理解模型决策过程。
摘要由CSDN通过智能技术生成

对随机森林进行可视化
安装一些需要的库:

pip install graphviz
pip install pydotplus

在Jupyter notebook 中进行随机森林可视化:

from sklearn import datasets
from sklearn.ensemble import RandomForestClassifier
from IPython.core.display import HTML, display
from sklearn import tree
import pydotplus


# 使用自带的iris数据
iris = datasets.load_iris()
X = iris.data
y = iris.target

# 训练模型,限制树的最大深度4
clf = RandomForestClassifier(max_depth=4)
#拟合模型
clf.fit(X, y)

estimators = clf.estimators_
for m in estimators:
    dot_data = tree.export_graphviz(m, out_file=None,
                         feature_names=iris.feature_names,
                         class_names=iris.target_names,
                         filled=True, rounded=True,
                         special_characters=True)
    graph = pydotplus.graph_from_dot_data(dot_data)
    # 使用ipython的终端jupyter notebook显示。
    svg = graph.create_svg()
    if hasattr(svg, "decode"):
         svg = svg.decode("utf-8")
     html = HTML(svg)
     display(html)

结果图就不放了

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值