sklearn 决策树可视化

来自google developer 的Machine Learning Recipes with Josh Gordon
Youtube链接
https://www.youtube.com/watch?v=cKxRvEZd3Mw&list=PLOU2XLYxmsIIuiBfYad6rFYQU_jL2ryal&index=1

生成决策树

这里使用了lris_flower_data_set
生成了一个认花的小树

import numpy as np
from sklearn.datasets import load_iris
from sklearn import tree
iris = load_iris()
test_idx=[0,50,100]

#train data
train_target =np.delete(iris.target,test_idx)
train_data = np.delete(iris.data,test_idx,axis = 0)

#testing fata
test_target = iris.target[test_idx]
test_data = iris.data[test_idx]
clf = tree.DecisionTreeClassifier()
clf.fit(train_data,train_target)
print(clf.predict(test_data))

这里总共有3类鸢尾花,每类50条数据,每组的第一个数据作为测试数据,剩余所有的数据作为训练数据

输出:

[0 1 2]

可视化

使用pydot
可以pip安装

from sklearn.externals.six import StringIO
import pydot

dot_data = StringIO()
tree.export_graphviz(clf, out_file=dot_data,
                        feature_names=iris.feature_names,
                        class_names=iris.target_names,
                        filled=True, rounded=True,
                        special_characters=True)
graph = pydot.graph_from_dot_data(dot_data.getvalue())
graph[0].write_pdf("iris.pdf")

iris.pdf:
这里写图片描述

Tips of 安装graphviz

首先需要pip安装graphviz包

pip install graghviz

但是仅仅安装python包会产生

RuntimeError: failed to execute ['dot', '-Tpdf', '-O', 'test-output/round-table.gv'], make sure the Graphviz executables are on your systems' path

解决方案:安装了anaconda可以

conda install graphviz

然后将anaconda\Library\bin\graphviz加入Path可以使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值