经典的Iris数据集
from sklearn.datasets import load_iris
iris = load_iris()
这里我们将创建两个版本:
from sklearn.ensemble import RandomForestClassifier
# Limit max depth
model = RandomForestClassifier(max_depth = 3, n_estimators=10)
# Train
model.fit(iris.data, iris.target)
# Extract single tree
estimator_limited = model.estimators_[5]
estimator_limited
----output
DecisionTreeClassifier(class_weight=None, criterion='gini', max_depth=3,
max_features='auto', max_leaf_nodes=None,
min_impurity_decrease=0.0, min_impurity_split=None,
min_samples_leaf=1, min_samples_split=2,
min_weight_fraction_leaf=0.0, presort=False,
random_state=1538259045, splitter='best')
# No max depth
model = RandomForestClassifier(max_depth = None, n_estimators=10)
model.fit(iris.data, iris.target)
estimator_nonlimited = model.estimators_[5]
from sklearn.tree import export_graphviz
export_graphviz(estimator_limited, out_file='tree_limited.dot', feature_names = iris.feature_names,
class_names = iris.target_names,
rounded = True, proportion = False, precision = 2, filled = True)
export_graphviz(estimator_nonlimited, out_file='tree_nonlimited.dot', feature_names = iris.feature_names,
class_names = iris.target_names,
rounded = True, proportion = False, precision = 2, filled = True)
!dot -Tpng tree_limited.dot -o tree_limited.png -Gdpi=600
from IPython.display import Image
Image(filename = 'tree_limited.png')
Image(filename = 'tree_nonlimited.png')
from sklearn.datasets import load_iris
iris = load_iris()
# Model (can also use single decision tree)
from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(n_estimators=10)
# Train
model.fit(iris.data, iris.target)
# Extract single tree
estimator = model.estimators_[5]
from sklearn.tree import export_graphviz
# Export as dot file
export_graphviz(estimator, out_file='tree.dot',
feature_names = iris.feature_names,
class_names = iris.target_names,
rounded = True, proportion = False,
precision = 2, filled = True)
# Convert to png
from subprocess import call
call(['dot', '-Tpng', 'tree.dot', '-o', 'tree.png', '-Gdpi=600'])
# Display in python
import matplotlib.pyplot as plt
plt.figure(figsize = (14, 18))
plt.imshow(plt.imread('tree.png'))
plt.axis('off');
plt.show();
将一棵决策树可视化可以帮助我们了解整个随机森林是如何做出预测的: 它不是随机分裂的,而是一系列有序的逻辑步骤。
在学习目前的主流的算法同时,这些经典的算法内部原理也要有所了解,毕竟这也是面试中经常会问到的。
如果你感觉这对你的工作学习有帮助,点赞关注一键三连,支持我的工作!
扫码加我好友进微信群|QQ群


原文作者:ChallengeHub;如有侵权,请联系管理员删除。