Zoy*_*oya 16 python tree pydot random-forest scikit-learn
我想绘制一个随机森林的决策树.所以,我创建以下代码:
clf = RandomForestClassifier(n_estimators=100)
import pydotplus
import six
from sklearn import tree
dotfile = six.StringIO()
i_tree = 0
for tree_in_forest in clf.estimators_:
if (i_tree <1):
tree.export_graphviz(tree_in_forest, out_file=dotfile)
pydotplus.graph_from_dot_data(dotfile.getvalue()).write_png('dtree'+ str(i_tree) +'.png')
i_tree = i_tree + 1
Run Code Online (Sandbox Code Playgroud)
但它没有产生任何东西..你知道如何从随机森林中绘制决策树吗?
谢谢,
use*_*745 24
假设已经安装了随机森林模型,首先应首先导入该export_graphviz函数:
from sklearn.tree import export_graphviz
Run Code Online (Sandbox Code Playgroud)
在您的for循环中,您可以执行以下操作来生成dot文件
export_graphviz(tree_in_forest,
feature_names=X.columns,
filled=True,
rounded=True)
Run Code Online (Sandbox Code Playgroud)
下一行生成一个png文件
os.system('dot -Tpng tree.dot -o tree.png')
Run Code Online (Sandbox Code Playgroud)
Mic*_*nyk 22
在 scikit-learn 中拟合随机森林模型后,您可以可视化随机森林中的各个决策树。下面的代码首先适合随机森林模型。
import matplotlib.pyplot as plt
from sklearn.datasets import load_breast_cancer
from sklearn import tree
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
# Load the Breast Cancer Dataset
data = load_breast_cancer()
df = pd.DataFrame(data.data, columns=data.feature_names)
df['target'] = data.target
# Arrange Data into Features Matrix and Target Vector
X = df.loc[:, df.columns != 'target']
y = df.loc[:, 'target'].values
# Split the data into training and testing sets
X_train, X_test, Y_train, Y_test = train_test_split(X, y, random_state=0)
# Random Forests in `scikit-learn` (with N = 100)
rf = RandomForestClassifier(n_estimators=100,
random_state=0)
rf.fit(X_train, Y_train)
Run Code Online (Sandbox Code Playgroud)
您现在可以可视化单个树。下面的代码可视化了第一个决策树。
fn=data.feature_names
cn=data.target_names
fig, axes = plt.subplots(nrows = 1,ncols = 1,figsize = (4,4), dpi=800)
tree.plot_tree(rf.estimators_[0],
feature_names = fn,
class_names=cn,
filled = True);
fig.savefig('rf_individualtree.png')
Run Code Online (Sandbox Code Playgroud)
下图是保存的内容。
因为这个问题要求树,如果你愿意,你可以从随机森林中可视化所有的估计器(决策树)。下面的代码可视化了上面拟合的随机森林模型中的前 5 个。
# This may not the best way to view each estimator as it is small
fn=data.feature_names
cn=data.target_names
fig, axes = plt.subplots(nrows = 1,ncols = 5,figsize = (10,2), dpi=900)
for index in range(0, 5):
tree.plot_tree(rf.estimators_[index],
feature_names = fn,
class_names=cn,
filled = True,
ax = axes[index]);
axes[index].set_title('Estimator: ' + str(index), fontsize = 11)
fig.savefig('rf_5trees.png')
Run Code Online (Sandbox Code Playgroud)
下图是保存的内容。
代码改编自这篇文章。
要从 scikit-learn 中的随机森林访问单个决策树,请使用estimators_属性:
rf = RandomForestClassifier()
# first decision tree
rf.estimators_[0]
Run Code Online (Sandbox Code Playgroud)
然后您可以使用标准方法可视化决策树:
export_textexport_graphviz方法绘图plot_tree使用 sklearn方法使用 matplotlib 进行绘图dtreeviz包进行树图绘制这篇文章中描述了具有示例输出的代码。
从随机森林中绘制单个决策树时,重要的是它可能已完全生长(默认超参数)。这意味着树可以非常深度。对我来说,深度大于 6 的树很难阅读。因此,如果需要树可视化,我将使用 < 7 构建随机森林。您可以查看本文max_depth中的示例可视化。
| 归档时间: |
|
| 查看次数: |
31470 次 |
| 最近记录: |