Machine Learning with Scikit-Learn and Tensorflow 6.1 决策树的训练与可视化

书籍信息
Hands-On Machine Learning with Scikit-Learn and Tensorflow
出版社: O’Reilly Media, Inc, USA
平装: 566页
语种: 英语
ISBN: 1491962291
条形码: 9781491962299
商品尺寸: 18 x 2.9 x 23.3 cm
ASIN: 1491962291

系列博文为书籍中文翻译
代码以及数据下载:https://github.com/ageron/handson-ml

为了理解决策树,让我们建立决策树并且观察决策树如何进行预测。以下代码基于iris数据集建立决策树。

from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
iris = load_iris()
X = iris.data[:, 2:] # petal length and width
y = iris.target

tree_clf = DecisionTreeClassifier(max_depth=2, random_state=42)
tree_clf.fit(X, y)
# output
# DecisionTreeClassifier(class_weight=None, 
#    criterion='gini', max_depth=2,
#    max_features=None, max_leaf_nodes=None,
#    min_samples_leaf=1, min_samples_split=2,
#    min_weight_fraction_leaf=0.0, presort=False, 
#    random_state=42, splitter='best')

我们可以通过export_graphviz将决策树可视化。

from sklearn.tree import export_graphviz
export_graphviz(
        tree_clf,
        out_file="iris_tree.dot",
        feature_names=iris.feature_names[2:],
        class_names=iris.target_names,
        rounded=True,
        filled=True
    )

我们可以利用graphviz将输出的.dot文件进行转化。

dot -Tpng iris_tree.dot -o iris_tree.png

译者注:
scikit-learn相关文档:http://scikit-learn.org/stable/modules/generated/sklearn.tree.export_graphviz.html
windows graphviz下载地址:http://www.graphviz.org/Download_windows.php(需要设置环境变量)

Machine Learning with Scikit-Learn and Tensorflow 6.1 决策树的训练与可视化_第1张图片

你可能感兴趣的:(机器学习)