最近在学习Peter Harrington的《机器学习实战》,代码与书中的略有不同,但可以顺利运行。

import matplotlib.pyplot as plt# 定义文本框和箭头格式
decisionNode = dict(boxstyle='sawtooth', fc='0.8')
leafNode = dict(boxstyle='round4', fc='0.8')
arrow_args = dict(arrowstyle='<-')# 使用文本注解绘制树节点
def plotNode(nodeTxt, cencerPt, parentPt, nodeType):createPlot.axl.annotate(nodeTxt, xy=parentPt, xycoords='axes fraction',xytext=cencerPt, textcoords='axes fraction',va='center', ha='center', bbox=nodeType, arrowprops=arrow_args)# 第一版的createPlot(),之后还需要修改
# def createPlot():
#     fig = plt.figure(1, facecolor='white')
#     fig.clf()
#     createPlot.ax1 = plt.subplot(111, frameon=False)
#     plotNode('a decision  node', (0.5, 0.1), (0.1, 0.5), decisionNode)
#     plotNode('a leaf node', (0.8, 0.1), (0.3, 0.8), leafNode)
#     plt.show()
# createPlot()
# 报错'function' object has no attribute 'axl',原因未知# 获取叶节点的数目
def getNumLeafs(mytree):numLeafs = 0firstStr = list(mytree.keys())[0]secondDict = mytree[firstStr]for key in secondDict.keys():if type(secondDict[key]).__name__=='dict':numLeafs += getNumLeafs(secondDict[key])else:numLeafs += 1return numLeafs# mytree = {'no surfacing': {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}}
# print(getNumLeafs(mytree))# 获取决策树的层数
def getTreeDepth(mytree):maxDepth = 0firstStr = list(mytree.keys())[0]secondDict = mytree[firstStr]for key in secondDict.keys():if type(secondDict[key]).__name__ == 'dict':thisDepth = 1 + getTreeDepth(secondDict[key])else:thisDepth = 1if thisDepth > maxDepth:maxDepth = thisDepthreturn maxDepth# mytree = {'no surfacing': {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}}
# print(getTreeDepth(mytree))# 在父子节点之间填充文本信息
def plotMidText(centerPt, parentPt, txtString):xMid = (parentPt[0] - centerPt[0]) / 2.0 + centerPt[0]yMid = (parentPt[1] - centerPt[1]) / 2.0 + centerPt[1]createPlot.axl.text(xMid, yMid, txtString)def plotTree(mytree, parentPt, nodeTxt):numLeafs = getNumLeafs(mytree)depth = getTreeDepth(mytree)firstSides = list(mytree.keys())firstStr = firstSides[0]  # 划分数据集的特征centerPt = (plotTree.xOff + (1.0 + float(numLeafs))/2.0/plotTree.totalW, plotTree.yOff)  # x轴右移,(1+叶节点数目)/(2*决策树宽度),y轴不变plotMidText(centerPt, parentPt, nodeTxt)  # 绘制父子节点之间的文本标签(对于划分数据集的特征,其实没有文本标签)plotNode(firstStr, centerPt, parentPt, decisionNode)  # 绘制父节点与指向子节点的箭头secondDict = mytree[firstStr]  # 划分数据集特征的取值plotTree.yOff = plotTree.yOff - 1.0 / plotTree.totalD  # y轴下移,1/决策树深度for key in secondDict.keys():# 如果分支下还有子树,调用函数本身,递归完成该分支的绘制if type(secondDict[key]).__name__ == 'dict':plotTree(secondDict[key], centerPt, str(key))# 如果分支下没有子树,仅一种分类结果,绘制叶子节点,添加父子节点之间的文本标签else:plotTree.xOff = plotTree.xOff + 1.0 / plotTree.totalW  # x轴右移,1/(2*决策树宽度)plotNode(secondDict[key], (plotTree.xOff, plotTree.yOff), centerPt, leafNode)  # 绘制叶子节点plotMidText((plotTree.xOff, plotTree.yOff), centerPt, str(key))  # 添加父子节点之间的文本标签plotTree.yOff = plotTree.yOff + 1.0/plotTree.totalD # y轴上移,恢复初始值,确保另外一个分支父节点的位置正确def createPlot(intree):fig = plt.figure(1, facecolor='white')  # 创建一个新图形,前景色为白色fig.clf()  # 清空绘图区axprops = dict(xticks=[], yticks=[])  # 定义坐标轴(空白)createPlot.axl = plt.subplot(111, frameon=False, **axprops)  # 创建子图,无边框,无坐标值plotTree.totalW = float(getNumLeafs(intree))   # 设置全局变量,记录决策树的宽带plotTree.totalD = float(getTreeDepth(intree))  # 设置全局变量,记录决策树的深度plotTree.xOff = -0.5 / plotTree.totalW  # 设置全局变量,追踪节点的x轴坐标plotTree.yOff = 1.0  # 设置全局变量,追踪节点的y轴坐标plotTree(intree, (0.5, 1.0), '')plt.show()# mytree = {'no surfacing': {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}}
# createPlot(mytree)
# mytree = {'no surfacing': {1: {'flippers': {0: 'no', 1: 'yes'}}, 0: 'no'}}
# createPlot(mytree)import matplotlib.pyplot as plt# 定义文本框和箭头格式
decisionNode = dict(boxstyle='sawtooth', fc='0.8')
leafNode = dict(boxstyle='round4', fc='0.8')
arrow_args = dict(arrowstyle='<-')# 使用文本注解绘制树节点
def plotNode(nodeTxt, cencerPt, parentPt, nodeType):createPlot.axl.annotate(nodeTxt, xy=parentPt, xycoords='axes fraction',xytext=cencerPt, textcoords='axes fraction',va='center', ha='center', bbox=nodeType, arrowprops=arrow_args)# 第一版的createPlot(),之后还需要修改
# def createPlot():
#     fig = plt.figure(1, facecolor='white')
#     fig.clf()
#     createPlot.ax1 = plt.subplot(111, frameon=False)
#     plotNode('a decision  node', (0.5, 0.1), (0.1, 0.5), decisionNode)
#     plotNode('a leaf node', (0.8, 0.1), (0.3, 0.8), leafNode)
#     plt.show()
# createPlot()
# 报错'function' object has no attribute 'axl',原因未知# 获取叶节点的数目
def getNumLeafs(mytree):numLeafs = 0firstStr = list(mytree.keys())[0]secondDict = mytree[firstStr]for key in secondDict.keys():if type(secondDict[key]).__name__=='dict':numLeafs += getNumLeafs(secondDict[key])else:numLeafs += 1return numLeafs# mytree = {'no surfacing': {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}}
# print(getNumLeafs(mytree))# 获取决策树的层数
def getTreeDepth(mytree):maxDepth = 0firstStr = list(mytree.keys())[0]secondDict = mytree[firstStr]for key in secondDict.keys():if type(secondDict[key]).__name__ == 'dict':thisDepth = 1 + getTreeDepth(secondDict[key])else:thisDepth = 1if thisDepth > maxDepth:maxDepth = thisDepthreturn maxDepth# mytree = {'no surfacing': {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}}
# print(getTreeDepth(mytree))# 在父子节点之间填充文本信息
def plotMidText(centerPt, parentPt, txtString):xMid = (parentPt[0] - centerPt[0]) / 2.0 + centerPt[0]yMid = (parentPt[1] - centerPt[1]) / 2.0 + centerPt[1]createPlot.axl.text(xMid, yMid, txtString)def plotTree(mytree, parentPt, nodeTxt):numLeafs = getNumLeafs(mytree)depth = getTreeDepth(mytree)firstSides = list(mytree.keys())firstStr = firstSides[0]  # 划分数据集的特征centerPt = (plotTree.xOff + (1.0 + float(numLeafs))/2.0/plotTree.totalW, plotTree.yOff)  # x轴右移,(1+叶节点数目)/(2*决策树宽度),y轴不变plotMidText(centerPt, parentPt, nodeTxt)  # 绘制父子节点之间的文本标签(对于划分数据集的特征,其实没有文本标签)plotNode(firstStr, centerPt, parentPt, decisionNode)  # 绘制父节点与指向子节点的箭头secondDict = mytree[firstStr]  # 划分数据集特征的取值plotTree.yOff = plotTree.yOff - 1.0 / plotTree.totalD  # y轴下移,1/决策树深度for key in secondDict.keys():# 如果分支下还有子树,调用函数本身,递归完成该分支的绘制if type(secondDict[key]).__name__ == 'dict':plotTree(secondDict[key], centerPt, str(key))# 如果分支下没有子树,仅一种分类结果,绘制叶子节点,添加父子节点之间的文本标签else:plotTree.xOff = plotTree.xOff + 1.0 / plotTree.totalW  # x轴右移,1/(2*决策树宽度)plotNode(secondDict[key], (plotTree.xOff, plotTree.yOff), centerPt, leafNode)  # 绘制叶子节点plotMidText((plotTree.xOff, plotTree.yOff), centerPt, str(key))  # 添加父子节点之间的文本标签plotTree.yOff = plotTree.yOff + 1.0/plotTree.totalD # y轴上移,恢复初始值,确保另外一个分支父节点的位置正确def createPlot(intree):fig = plt.figure(1, facecolor='white')  # 创建一个新图形,前景色为白色fig.clf()  # 清空绘图区axprops = dict(xticks=[], yticks=[])  # 定义坐标轴(空白)createPlot.axl = plt.subplot(111, frameon=False, **axprops)  # 创建子图,无边框,无坐标值plotTree.totalW = float(getNumLeafs(intree))   # 设置全局变量,记录决策树的宽带plotTree.totalD = float(getTreeDepth(intree))  # 设置全局变量,记录决策树的深度plotTree.xOff = -0.5 / plotTree.totalW  # 设置全局变量,追踪节点的x轴坐标plotTree.yOff = 1.0  # 设置全局变量,追踪节点的y轴坐标plotTree(intree, (0.5, 1.0), '')plt.show()# mytree = {'no surfacing': {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}}
# createPlot(mytree)
# mytree = {'no surfacing': {1: {'flippers': {0: 'no', 1: 'yes'}}, 0: 'no'}}
# createPlot(mytree)

机器学习实战——绘制决策树(代码)相关推荐

  1. apriori算法代码_资源 | 《机器学习实战》及代码(基于Python3)

    〇.<机器学习实战> 今天推荐给大家的是<机器学习实战>这本书. 机器学习作为人工智能研究领域中一个极其重要的研究方向(一文章看懂人工智能.机器学习和深度学习),在当下极其热门 ...

  2. 机器学习实战之决策树熵的概述

    机器学习实战之决策树熵的概述 一.决策树简介 二.决策树的一般流程 三.决策树构建的准备工作 1.特征选择 (1)香农熵 (2)编写代码计算经验熵 (3)信息增益 (4)编写代码计算信息增益 2.决策 ...

  3. 《机器学习实战》配套代码下载

    <机器学习实战>配套代码资源下载网址:http://www.ituring.com.cn/book/1021(图灵社区),网址里有随书下载,可以下载配套资源.

  4. 机器学习实战 支持向量机SVM 代码解析

    机器学习实战 支持向量机SVM 代码解析 <机器学习实战>用代码实现了算法,理解源代码更有助于我们掌握算法,但是比较适合有一定基础的小伙伴.svm这章代码看起来风轻云淡,实则对于新手来说有 ...

  5. 机器学习实战之决策树(一)构造决策树

    决策树(一)构造决策树 1.简介 1.1 优缺点 1.2 流程 1.3 决策树的构造 1.4 海洋生物数据 2.信息增益 2.1 几个概念 2.2 计算给定数据集的熵 3 划分数据集 3.1 按照给定 ...

  6. 刻意练习:机器学习实战 -- Task01. 决策树

    背景 这是我们为拥有 Python 基础的同学推出的精进技能的"机器学习实战" 刻意练习活动,这也是我们本学期推出的第三次活动了. 我们准备利用8周时间,夯实机器学习常用算法,完成 ...

  7. 《机器学习实战》—— 决策树

    目录 一.决策树的构造 1. 信息增益 2. 划分数据集 3. 递归构建决策树 二.在 Python 中使用 Matplotlib 注解绘制树形图 1. Matplotlib 2. 构造注解树 三.测 ...

  8. 《机器学习实战》——决策树

    一 决策树 决策树是什么?决策树(decision tree)是一种基本的分类与回归方法.举个通俗易懂的例子,如下图所示的流程图就是一个决策树,长方形代表判断模块(decision block),椭圆 ...

  9. 机器学习实战之决策树

    你是否玩过二十个问题的游戏,游戏的规则很简单:参与游戏的一方在脑海里想某个事物,其他参与者向他提问题,只允许提20个问题,问题的答案也只能用对或错回答.问问题的人通过 推断分解,逐步缩小待猜测事物的范 ...

最新文章

  1. MySQL下备份和恢复简单介绍
  2. 苹果首任AI总监Ruslan Salakhutdinov:如何应对深度学习的两大挑战?(附视频)
  3. 【临实战】使用 Python 处理 Nginx 日志
  4. 重学前端-学习笔记-JavaScript对象
  5. 区块链是什么鬼,未来30万亿贷款市场或将激活?
  6. SHOW INDEX FROM 表名,查看mysql表中有哪些索引
  7. C#LeetCode刷题之#13-罗马数字转整数(Roman to Integer)
  8. 子进程中获取父进程id_进程全家桶,看这一篇就够了 | 原力计划
  9. 零基础小白学习UI设计的4个步骤
  10. Hudson Jameson将在柏林硬分叉后卸任以太坊基金会社区经理
  11. 中建股份400亿大型IPO获“特批”
  12. OAuth2.0认证流程原理
  13. Win虚拟机查询不到自己的IP地址
  14. 编写c语言程序解一元一次方程,一元方程计算器1.0的代码(C语言实现)
  15. 真正的黑科技,完美分离人声伴奏~
  16. 整理下关于Visual Foxpro的技术
  17. 寂寞情来情去——忆纳兰词
  18. Mysql将txt文件导入数据库采坑 load data local infile
  19. 物联网卡要求实名认证的真正原因你知道吗?
  20. 【WebAPI 验证】给 webapi加上token 验证(包括上传文件方法)

热门文章

  1. 关于BIOS的入口地址0xFFFF0
  2. 英语单词记忆 词源法-思维导图 序
  3. OpenCV中的基本图像操作
  4. PS人物快速换装--纯色换成碎花装
  5. ACM-ICPC 2018 焦作赛区网络预赛 L Poor God Water(BM算法)
  6. PAT_乙级_1001_筱筱
  7. 电商系统,商品属性表和功能设计,可用于各种实体的属性
  8. Redis缓存——(分布式锁)
  9. 超炫的html5擦除效果,超炫html5效果代码(需浏览器支持)
  10. 高级验证方法学()-Mentor-笔记