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

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

  1. #coding=utf-8
  2. import matplotlib
  3. matplotlib.use('Agg')
  4. import matplotlib.pyplot as plt # 载入 pyplot API
  5. import os, sys
  6. import time
  7.  
  8. decisionNode = dict(boxstyle="sawtooth", fc="0.8") # 注(a)
  9. leafNode = dict(boxstyle="round4", fc="0.8")
  10. arrow_args = dict(arrowstyle="<-") # 箭头样式
  11.  
  12. def plotNode(Nodename, centerPt, parentPt, nodeType): # centerPt节点中心坐标 parentPt 起点坐标
  13. creatPlot.ax1.annotate(Nodename, xy=parentPt, xycoords='axes fraction', xytext=centerPt, textcoords='axes fraction', va="center", ha="center", bbox=nodeType, arrowprops=arrow_args) # 注(b)
  14.  
  15. def getNumleafs(mytree): # 获得叶节点数目,输入为我们前面得到的树(字典)
  16. Numleafs = 0 # 初始化
  17. firstStr = list(mytree.keys())[0] # 注(a) 获得第一个key值(根节点) 'no surfacing'
  18. secondDict = mytree[firstStr] # 获得value值 {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}
  19. for key in secondDict.keys(): # 键值:0 和 1
  20. if type(secondDict[key]).__name__=='dict': # 判断如果里面的一个value是否还是dict
  21. Numleafs += getNumleafs(secondDict[key]) # 递归调用
  22. else:
  23. Numleafs += 1
  24. return Numleafs
  25.  
  26. def getTreeDepth(mytree):
  27. maxDepth = 0
  28. firstStr = list(mytree.keys())[0]
  29. secondDict = mytree[firstStr]
  30. for key in secondDict.keys(): # 键值:0 和 1
  31. thisDepth = 0
  32. if type(secondDict[key]).__name__=='dict': # 判断如果里面的一个value是否还是dict
  33. thisDepth = 1 + getTreeDepth(secondDict[key]) # 递归调用
  34. else:
  35. thisDepth = 1
  36. if thisDepth > maxDepth:
  37. maxDepth = thisDepth
  38. return maxDepth
  39.  
  40. def plotMidText(cntrPt, parentPt, txtString): # 在两个节点之间的线上写上字
  41. xMid = (parentPt[0]-cntrPt[0])/2.0 + cntrPt[0]
  42. yMid = (parentPt[1]-cntrPt[1])/2.0 + cntrPt[1]
  43. creatPlot.ax1.text(xMid, yMid, txtString) # text() 的使用
  44.  
  45. def plotTree(myTree, parentPt, nodeName): # 画树
  46. numleafs = getNumleafs(myTree)
  47. depth = getTreeDepth(myTree)
  48. firstStr = myTree.keys()[0]
  49. cntrPt = (plotTree.xOff+(0.5/plotTree.totalw+float(numleafs)/2.0/plotTree.totalw), plotTree.yOff)
  50. plotMidText(cntrPt, parentPt, nodeName)
  51. plotNode(firstStr, cntrPt, parentPt, decisionNode)
  52. secondDict = myTree[firstStr]
  53. plotTree.yOff = plotTree.yOff - 1.0/plotTree.totalD # 减少y的值,将树的总深度平分,每次减少移动一点(向下,因为树是自顶向下画的)
  54. for key in secondDict.keys():
  55. if type(secondDict[key]).__name__=='dict':
  56. plotTree(secondDict[key], cntrPt, str(key))
  57. else:
  58. plotTree.xOff = plotTree.xOff + 1.0/plotTree.totalw
  59. plotNode(secondDict[key], (plotTree.xOff, plotTree.yOff), cntrPt, leafNode)
  60. plotMidText((plotTree.xOff, plotTree.yOff), cntrPt, str(key))
  61. plotTree.yOff = plotTree.yOff + 1.0/plotTree.totalD
  62.  
  63. def creatPlot(inTree): # 使用的主函数
  64. fig = plt.figure(figsize=(200,200), facecolor='white')
  65. fig.clf() # 清空绘图区
  66. axprops = dict(xticks=[], yticks=[]) # 创建字典 存储=====有疑问???=====
  67. creatPlot.ax1 = plt.subplot(111, frameon=False, **axprops) # ===参数的意义?===
  68. plotTree.totalw = float(getNumleafs(inTree))
  69. plotTree.totalD = float(getTreeDepth(inTree)) # 创建两个全局变量存储树的宽度和深度
  70. print 'tree width =', plotTree.totalw
  71. print 'tree height =', plotTree.totalD
  72. plotTree.xOff = -0.5/plotTree.totalw # 追踪已经绘制的节点位置 初始值为 将总宽度平分 在取第一个的一半
  73. plotTree.yOff = 1.0
  74. plotTree(inTree, (0.5,1.0), '') # 调用函数,并指出根节点源坐标
  75. plt.savefig('images/tree2.png', format='png', dpi=100)
  76.  
  77. trees = []
  78. try:
  79. fin = open(sys.argv[1])
  80. line = fin.readline()
  81. trees = eval(line)
  82. #print trees
  83. except:
  84. print 'load tree error'
  85. raise
  86. if(len(sys.argv) == 1):
  87. trees = {'no surfacing': { 0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}}
  88. t1 = time.clock()
  89. creatPlot(trees)
  90. t2 = time.clock()
  91. 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. SELECT INSTR(120,0000); 真

    sql 排故 SELECT  INSTR(120,0000);  真

  2. 0mq

  3. 正则表达式pattern的匹配格式

    0> 匹配 -------------------------------------------------------------------------------- (pattern)  ...

  4. 深度学习入门-4.1 AND.py 源码分析

    源代码 ------------------------------------------------------------------------------------------------ ...

  5. 移动web开发适配rem

    移动的meta标签 <meta  name="viewport" content="width=device-width, initial-scale=1,user ...

  6. ubuntu主板信息

    root:~# sudo dmidecode |grep -A16 "System Information$"sudo: 无法解析主机:phone-TPOWER-X79System ...

  7. Hibernate写hql语句与不写hql语句的区别?

    写hql语句与不写hql语句的区别? 写hql语句:书写HQL语句,所有的查询与投影的设计均使用HQL语句完成. 不写hql语句:没有任何查询语句,所有的查询与投影的设计使用面向对象格式完成. 二者选 ...

  8. React引入,运行

    1.引入 <script src="https://cdn.bootcss.com/react/15.5.4/react.min.js"></script> ...

  9. sql 简单查询修改

    .group by order by from webdb where gathtrime between '2017-06-14 00:00:00' and '2017-06-14 23:59:59 ...

  10. 「LuoguP1799」 数列_NOI导刊2010提高(06)

    题目描述 虽然msh长大了,但她还是很喜欢找点游戏自娱自乐.有一天,她在纸上写了一串数字:1,1,2,5,4.接着她擦掉了一个l,结果发现剩下1,2,4都在自己所在的位置上,即1在第1位,2在第2位, ...