赞
踩
随机森林是多棵决策树的组合,使用scikit-learn时没有直接的方法显示随机森林,只能拆解成单棵树来显示。使用随机森林的属性clf.estimators_获取随机森林的决策树列表( 注意,estimators后边有一个下划线 ’ _’ )
from sklearn import datasets from sklearn.ensemble import RandomForestClassifier from IPython.display import Image 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 index, model in enumerate(Estimators): filename = 'iris_' + str(index) + '.pdf' dot_data = tree.export_graphviz(model , 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) graph.write_pdf(filename)
我们看一下结果为:
我们生成了100个PDF文件,每个文件为一个决策树:
。。。。。
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。