基础环境:
anaconda3-5.2.0
Python3.6
win10x64
一,win10安装graphviz-2.38.msi
官网下载:https://graphviz.gitlab.io/_pages/Download/Download_windows.html
网盘下载:https://pan.baidu.com/s/1acgCB8nFwxkryvKivCb1Pw 提取码:l6tw
二,Python安装graphviz
pip3 install graphviz
三,Python安装pydotplus
pip3 install pydotplus
四,代码模拟鸢尾花决策树分类
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 31 16:51:08 2019
@author: 86182
"""
from sklearn.datasets import load_iris
from sklearn import tree
import pydotplus
#用于划分训练集与测试集
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
#加载数据
iris = load_iris()
#划分训练集与测试集
(training_inputs, testing_inputs, training_classes, testing_classes)
=train_test_split(iris.data, iris.target,test_size=0.4, random_state=1)
# 构建模型
clf = tree.DecisionTreeClassifier()
clf = clf.fit(training_inputs, training_classes)
#测试值预测
y_predict = clf.predict(testing_inputs)
#预测值和测试值打分
score = classification_report(testing_classes, y_predict)
print(score)
# 保存模型
with open("iris.dot", 'w') as f:
f = tree.export_graphviz(clf, out_file=f)
# 画图,保存到pdf文件
# 设置图像参数
dot_data = tree.export_graphviz(clf, 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)
# 保存图像到pdf文件
graph.write_pdf("iris.pdf")
|
|