
上QQ阅读APP看本书,新人免费读10天
设备和账号都新为新人
3.2 Matplotlib注释绘制树形图
上节已经学习了如何从数据集中创建树,然而字典的表示形式非常不易于理解,并且直接绘制图形也比较困难。本节将使用Matplotlib库创建树形图。决策树的主要优点就是直观、易于理解,如果不能将其直观地显示出来,就无法发挥其优势。
可视化需要用到的函数如下:
● getNumLeafs:获取决策树叶子节点的数目。
● getTreeDepth:获取决策树的层数。
● plotNode:绘制节点。
● plotMidText:标注有向边属性值。
● plotTree:绘制决策树。
● createPlot:创建绘制面板。
下面对可视化决策树的程序进行详细注释,直接看代码,调试查看即可。为了显示中文,需要设置FontProperties,代码编写如下:












运行程序,输出如下,效果如图3-3所示。


图3-3 决策树实例
可以看到决策树绘制完成。plotNode函数的工作就是绘制各个节点,比如,是否有自己的房子、是否有工作,包括内节点和叶子节点。plotMidText函数的工作就是绘制各个有向边的属性,如各个有向边的0和1。