折腾了一大圈儿,发现还是anaconda比较干脆利落。爽!两步走~~~
为了配合树形图可视化故事情节的发展而做的前情提要——数据处理,可以直接copy。
import numpy as np
import pandas as pd
from pandas import Series,DataFrame
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
# data
def create_data():
iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df['label'] = iris.target
df.columns = ['sepal length', 'sepal width', 'petal length', 'petal width', 'label']
data = np.array(df.iloc[:100, [0, 1, -1]])
# print(data)
return data[:,:2], data[:,-1]
X, y = create_data()
X_train, X_test, y_train1, y_test = train_test_split(X, y, test_size=0.3)
####决策树的生成代码
from sklearn.tree import DecisionTreeClassifier
from sklearn.tree import export_graphviz
import graphviz
import pydot
import os
clf = DecisionTreeClassifier()
clf.fit(X_train, y_train,)
clf.score(X_test, y_test)
将dot文件转换成png格式的图片
tree_pic = export_graphviz(clf, out_file="tree.dot", rounded = True, precision = 1)
(graph, ) = pydot.graph_from_dot_file("tree.dot")
# Write graph to a png file
graph.write_png('tree.png')
官网下载:
https://graphviz.gitlab.io/_pages/Download/Download_windows.html
安装过程简单到略。
参考这个吧: link.
另外
Win+R一下,cmd,输入命令: cd /D D:\graphviz-2.38\bin
切换到我的安装路径D:\graphviz-2.38\bin
若tree.dot的文件搁在该文件夹(D:\graphviz-2.38\bin)
在cmd中执行dot -Tpng tree.dot -o tree.png
也能出结果。
多总结多记录,好记性不如敲键盘