Graphviz 是一个绘图工具集, 可以用 The DOT Language 的 DSL 来绘图。用 dot 写好脚本之后,使用不同的布局引擎来对脚本解析,生成图片,支持 PNG、PDF 等格式。Graphviz 有好几个布局引擎,一般使用的有dot
(有向图) 和 circo
(环形布局),其他的较少使用。
Graphviz
包含 3 种图形元素,图(graph)
, 节点(node)
和边(edge)
。每个元素都可以具有各自的属性,用来定义字体,样式,颜色,形状等。
安装
-
安装
graphviz
进程1 2 3 4 5
Mac brew install graphviz ubuntu sudo apt-get install graphviz
或者到官网下载页面中, 找到对应平台的安装包安装。
-
安装
python-graphviz
模块1
sudo pip install graphviz
问题描述:
基本用法
通过实例化对象创建图形
以下是基于sklearn库的CART算法示例代码。通过构建决策树(采用Gini作为指标)对随机生成(通过np.random.randint方法)的数字进行分类,自变量X为100×4的矩阵,随机生成的数字大于10,因变量Y为大于2的100×1矩阵。树的最大深度限制为3层,训练完成之后将树可视化显示。
import numpy as np
import random
from sklearn import tree
from graphviz import Source
np.random.seed(42)
X =np.random.randint(10,size=(100,4))
Y =np.random.randint(2,size=100)
a =np.column_stack((Y,X))
clf =tree.DecisionTreeClassifier(criterion='gini',max_depth=3)
clf =clf.fit(X,Y)
graph =Source(tree.export_graphviz(clf,out_file=None))
graph.format ='png'
graph.render('cart_tree',view=True)
jupyter notebook运行,此时出现问题:UnicodeDecodeError: ‘utf-8’ codec can’t decode byte 0xd5 in position 2: invalid continuation byte该问题表明解码器错误。
尝试解决方法:
1.查看Anaconda3\envs\tensorflow1\Lib\site-packages\graphviz\.compat.py
加入以下代码:
PY2 = sys.version_info[0] == 2
if not PY2:
text_type = str
string_types = (str,)
unichr = chr
int_types = (int,)
iteritems = lambda x: iter(x.items())
else:
text_type = unicode
string_types = (str, unicode)
unichr = unichr
int_types = (int, long)
iteritems = lambda x: x.iteritems()
未成功
2.pip uninstall graphviz
pip install graphviz
或者
conda uinstall graphviz
conda install graphviz (如果报错,安装python-graphviz
模块: conda install python-graphviz)
再次运行:成功
生成cart_tree.png
基本思想:从根节点出发,测试不同的特征属性,按照结果的不同选择分支,最终落到某一叶子节点,获得分类结果。