1、trees = {'no surfacing': { 0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}}

2、从我的文件trees.txt里读的决策树,也是一个递归字典表示

#coding=utf-8
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt # 载入 pyplot API
import os, sys
import time decisionNode = dict(boxstyle="sawtooth", fc="0.8") # 注(a)
leafNode = dict(boxstyle="round4", fc="0.8")
arrow_args = dict(arrowstyle="<-") # 箭头样式 def plotNode(Nodename, centerPt, parentPt, nodeType): # centerPt节点中心坐标 parentPt 起点坐标
creatPlot.ax1.annotate(Nodename, xy=parentPt, xycoords='axes fraction', xytext=centerPt, textcoords='axes fraction', va="center", ha="center", bbox=nodeType, arrowprops=arrow_args) # 注(b) def getNumleafs(mytree): # 获得叶节点数目,输入为我们前面得到的树(字典)
Numleafs = 0 # 初始化
firstStr = list(mytree.keys())[0] # 注(a) 获得第一个key值(根节点) 'no surfacing'
secondDict = mytree[firstStr] # 获得value值 {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}
for key in secondDict.keys(): # 键值:0 和 1
if type(secondDict[key]).__name__=='dict': # 判断如果里面的一个value是否还是dict
Numleafs += getNumleafs(secondDict[key]) # 递归调用
else:
Numleafs += 1
return Numleafs def getTreeDepth(mytree):
maxDepth = 0
firstStr = list(mytree.keys())[0]
secondDict = mytree[firstStr]
for key in secondDict.keys(): # 键值:0 和 1
thisDepth = 0
if type(secondDict[key]).__name__=='dict': # 判断如果里面的一个value是否还是dict
thisDepth = 1 + getTreeDepth(secondDict[key]) # 递归调用
else:
thisDepth = 1
if thisDepth > maxDepth:
maxDepth = thisDepth
return maxDepth def plotMidText(cntrPt, parentPt, txtString): # 在两个节点之间的线上写上字
xMid = (parentPt[0]-cntrPt[0])/2.0 + cntrPt[0]
yMid = (parentPt[1]-cntrPt[1])/2.0 + cntrPt[1]
creatPlot.ax1.text(xMid, yMid, txtString) # text() 的使用 def plotTree(myTree, parentPt, nodeName): # 画树
numleafs = getNumleafs(myTree)
depth = getTreeDepth(myTree)
firstStr = myTree.keys()[0]
cntrPt = (plotTree.xOff+(0.5/plotTree.totalw+float(numleafs)/2.0/plotTree.totalw), plotTree.yOff)
plotMidText(cntrPt, parentPt, nodeName)
plotNode(firstStr, cntrPt, parentPt, decisionNode)
secondDict = myTree[firstStr]
plotTree.yOff = plotTree.yOff - 1.0/plotTree.totalD # 减少y的值,将树的总深度平分,每次减少移动一点(向下,因为树是自顶向下画的)
for key in secondDict.keys():
if type(secondDict[key]).__name__=='dict':
plotTree(secondDict[key], cntrPt, str(key))
else:
plotTree.xOff = plotTree.xOff + 1.0/plotTree.totalw
plotNode(secondDict[key], (plotTree.xOff, plotTree.yOff), cntrPt, leafNode)
plotMidText((plotTree.xOff, plotTree.yOff), cntrPt, str(key))
plotTree.yOff = plotTree.yOff + 1.0/plotTree.totalD def creatPlot(inTree): # 使用的主函数
fig = plt.figure(figsize=(200,200), facecolor='white')
fig.clf() # 清空绘图区
axprops = dict(xticks=[], yticks=[]) # 创建字典 存储=====有疑问???=====
creatPlot.ax1 = plt.subplot(111, frameon=False, **axprops) # ===参数的意义?===
plotTree.totalw = float(getNumleafs(inTree))
plotTree.totalD = float(getTreeDepth(inTree)) # 创建两个全局变量存储树的宽度和深度
print 'tree width =', plotTree.totalw
print 'tree height =', plotTree.totalD
plotTree.xOff = -0.5/plotTree.totalw # 追踪已经绘制的节点位置 初始值为 将总宽度平分 在取第一个的一半
plotTree.yOff = 1.0
plotTree(inTree, (0.5,1.0), '') # 调用函数,并指出根节点源坐标
plt.savefig('images/tree2.png', format='png', dpi=100) trees = []
try:
fin = open(sys.argv[1])
line = fin.readline()
trees = eval(line)
#print trees
except:
print 'load tree error'
raise
if(len(sys.argv) == 1):
trees = {'no surfacing': { 0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}}
t1 = time.clock()
creatPlot(trees)
t2 = time.clock()
print t2 - t1

ps:参考博客[http://blog.csdn.net/ifruoxi/article/details/53150129]

Linux下用matplotlib画决策树的更多相关文章

  1. linux下,matplotlib遇到的相关问题以及解决方法

    1.在linux下运行matplotlib程序时,matplotlib的安装. 根据不同的linux系统继续相关安装: Debian / Ubuntu : sudo apt-get install p ...

  2. Linux下画原理图和PCB

    Linux下画原理图和PCB Windows下大名鼎鼎的Allegro和经典的Protel 99SE都是不支持Linux操作系统的.做Linux驱动开发免不了要看一下原理图和PCB. 一般的做法有三种 ...

  3. Linux下Power Management开发总结

    本文作为一个提纲挈领的介绍性文档,后面会以此展开,逐渐丰富. 1. 前言 在 <开发流程>中介绍了PM开发的一般流程,重点是好的模型.简单有效的接口参数.可量化的测试环境以及可独性强的输出 ...

  4. python中matplotlib画折线图实例(坐标轴数字、字符串混搭及标题中文显示)

    最近在用python中的matplotlib画折线图,遇到了坐标轴 "数字+刻度" 混合显示.标题中文显示.批量处理等诸多问题.通过学习解决了,来记录下.如有错误或不足之处,望请指 ...

  5. Linux下配置Java环境变量

    今天开始简单的学习了一下在Linux下安装jdk 写下来总结一下以便后来的查找和复习 首先下载Linux版的jdk我这里使用的jdk1.7:http://download.oracle.com/otn ...

  6. linux下dup/dup2函数的用法

    系统调用dup和dup2能够复制文件描述符.dup返回新的文件文件描述符(没有用的文件描述符最小的编号).dup2可以让用户指定返回的文件描述符的值,如果需要,则首先接近newfd的值,他通常用来重新 ...

  7. linux下的X server:linux图形界面原理

    linux下的X server:linux图形界面原理   Moblin Core是在Gnome Mobile的平台上建立.我以前玩Linux,提交的都和图像没有关系,连Xwindows都不用启动,开 ...

  8. linux下阅读源代码的工具

    说来真是惭愧呀.一直在用VIM 做开发.却不知道VI 里还有这么好使的工具.以前一直都是用: find -type f -print | xargs grep -i **** 在源代码里查找. 原来L ...

  9. Linux 下实现控制屏幕显示信息和光标的状态

    //display.h /************************************************************* FileName : display.h File ...

随机推荐

  1. <转载>调制与解调电路详解

    原文链接:http://www.elecfans.com/analog/20120509270848_4.html 调幅和检波电路 广播和无线电通信是利用调制技术把低频声音信号加到高频信号上发射出去的 ...

  2. extjs 4 checkboxgroup Panel的简单用法

    Ext.require([ 'Ext.tree.*', 'Ext.data.*', 'Ext.window.MessageBox', 'Ext.tip.*' ]); Ext.onReady(funct ...

  3. jsp 中 jstl c:if等标签失效问题

    <c:if test="${page == 1}"> ${s.index+1} </c:if> <c:if test="${page > ...

  4. redis03----集合 set 相关命令

    集合 set 相关命令 集合的性质: 唯一性,无序性,确定性 注: 在string和link的命令中,可以通过range 来访问string中的某几个字符或某几个元素 但,因为集合的无序性,无法通过下 ...

  5. HDU1693 Eat the Trees —— 插头DP

    题目链接:https://vjudge.net/problem/HDU-1693 Eat the Trees Time Limit: 4000/2000 MS (Java/Others)    Mem ...

  6. Ubuntu安装mycli,让mysql命令行可以自动提示

    安装mycli 1.确保有安装python 2.确保有安装pip 3.进入su模式,以管理员身份安装 4.安装 pip install -U mycli 5.登录 mycli -u root 很好很强 ...

  7. 使用 Word 2013 维护博客

    博客的发布.修改是一件非常耗时.耗精力的事情.借助 Word 2013,维护博客将变得非常简单. 1 新建博客文章 运行 Word 2013,新建文档.如下图所示: 图1 鼠标左键单击上图的" ...

  8. I.MX6 2014 u-boot 测试修改

    /************************************************************************* * I.MX6 2014 u-boot 测试修改 ...

  9. c/c++内存机制(一)(原)

    一:C语言中的内存机制 在C语言中,内存主要分为如下5个存储区: (1)栈(Stack):位于函数内的局部变量(包括函数实参),由编译器负责分配释放,函数结束,栈变量失效. (2)堆(Heap):由程 ...

  10. DLL远程注入实例

    一般情况下,每个进程都有自己的私有空间,理论上,别的进程是不允许对这个私人空间进行操作的,但是,我们可以利用一些方法进入这个空间并进行操作,将自己的代码写入正在运行的进程中,于是就有了远程注入了. 对 ...