《机器学习实战》第三章 3.2在python 中使用matplotlib注解绘制树形图

本文通过实战演示如何利用Python中的matplotlib库实现决策树的可视化。不仅介绍了如何定义节点样式、绘制节点及箭头,还详细解释了如何通过递归算法构建整个决策树,并最终展示在屏幕上。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

《机器学习实战》系列博客主要是实现并理解书中的代码,相当于读书笔记了。毕竟实战不能光看书。动手就能遇到许多奇奇怪怪的问题。博文比较粗糙,需结合书本。博主边查边学,水平有限,有问题的地方评论区请多指教。书中的代码和数据,网上有很多请自行下载。

3.2.1Matplotlib注解

注解工具 annotations
这段代码有点烦琐,出现很多绘图函数,可以查看matplotlib 文档

使用文本注解绘制树节点

#coding:utf-8
import matplotlib.pyplot as plt

# 定义决策树决策结果的属性,用字典来定义  
# 下面的字典定义也可写作 decisionNode={boxstyle:'sawtooth',fc:'0.8'}  
# boxstyle为文本框的类型,sawtooth是锯齿形,fc是边框线粗细  
decisionNode = dict(boxstyle="sawtooth", fc="0.8")
leafNode = dict(boxstyle="round4", fc="0.8")
arrow_args = dict(arrowstyle="<-")

def plotNode(nodeTxt, centerPt, parentPt, nodeType):
    # annotate是关于一个数据点的文本  
    # nodeTxt为要显示的文本,centerPt为文本的中心点,箭头所在的点,parentPt为指向文本的点 
    createPlot.ax1.annotate(nodeTxt, xy=parentPt,  xycoords='axes fraction',
             xytext=centerPt, textcoords='axes fraction',
             va="center", ha="center", bbox=nodeType, arrowprops=arrow_args )

def createPlot():     
    fig = plt.figure(1,facecolor='white') # 定义一个画布,背景为白色
    fig.clf() # 把画布清空
    # createPlot.ax1为全局变量,绘制图像的句柄,subplot为定义了一个绘图,
    #111表示figure中的图有1行1列,即1个,最后的1代表第一个图 
    # frameon表示是否绘制坐标轴矩形 
    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() 

命令行输入

>>> import treePlotter
>>> treePlotter.createPlot()

这里写图片描述

3.2.2 构造注解树

树在python中用嵌套字典存储
例 :>>> myTree
{‘no surfacing’: {0: ‘no’, 1: {‘flippers’: {0: ‘no’, 1: ‘yes’}}}}
键值是字典则是判断结点,否则是叶子节点

获取叶子结点数和层数

def getNumLeafs(myTree):
    numLeafs = 0
    firstStr = myTree.keys()[0] #字典的第一个键,即树的一个结点
    secondDict = myTree[firstStr]  #这个键的值,即该结点的所有子树
    for key in secondDict.keys():
        if type(secondDict[key]).__name__=='dict':#test to see if the nodes are dictonaires, if not they are leaf nodes
            numLeafs += getNumLeafs(secondDict[key])
        else:   numLeafs +=1
    return numLeafs

def getTreeDepth(myTree):
    maxDepth = 0
    firstStr = myTree.keys()[0]
    secondDict = myTree[firstStr]
    for key in secondDict.keys():
        if type(secondDict[key]).__name__=='dict':
            thisDepth = 1 + getTreeDepth(secondDict[key])
        else:   thisDepth = 1
        if thisDepth > maxDepth: maxDepth = thisDepth
    return maxDepth

函数retrieveTree 创建两棵树,用来测试

>>> import treePlotter 
>>> mytree =  treePlotter.retrieveTree(0)
>>> treePlotter.getNumLeafs(mytree)
3
>>> treePlotter.getTreeDepth(mytree)
2

PlotTree 函数

感觉叶子横坐标放的位置还没理解的很清楚

def createPlot(inTree):
    fig = plt.figure(1, facecolor='white')
    fig.clf()
    axprops = dict(xticks=[], yticks=[])# 定义横纵坐标轴,无内容  
    #createPlot.ax1 = plt.subplot(111, frameon=False, **axprops) # 绘制图像,无边框,无坐标轴  
    createPlot.ax1 = plt.subplot(111, frameon=False) 
    plotTree.totalW = float(getNumLeafs(inTree))   #全局变量宽度 = 叶子数
    plotTree.totalD = float(getTreeDepth(inTree))  #全局变量高度 = 深度
    #图形的大小是0-1 ,0-1
    plotTree.xOff = -0.5/plotTree.totalW;  #例如绘制3个叶子结点,坐标应为1/3,2/3,3/3
    #但这样会使整个图形偏右因此初始的,将x值向左移一点。
    plotTree.yOff = 1.0;
    plotTree(inTree, (0.5,1.0), '')
    plt.show()

def plotTree(myTree, parentPt, nodeTxt):
    numLeafs = getNumLeafs(myTree)  #当前树的叶子数
    depth = getTreeDepth(myTree) #没有用到这个变量
    firstStr = myTree.keys()[0]   
    #cntrPt文本中心点   parentPt 指向文本中心的点 
    cntrPt = (plotTree.xOff + (1.0 + float(numLeafs))/2.0/plotTree.totalW, plotTree.yOff)
    plotMidText(cntrPt, parentPt, nodeTxt) #画分支上的键
    plotNode(firstStr, cntrPt, parentPt, decisionNode)
    secondDict = myTree[firstStr]
    plotTree.yOff = plotTree.yOff - 1.0/plotTree.totalD #从上往下画
    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 plotMidText(cntrPt, parentPt, txtString):
    xMid = (parentPt[0]-cntrPt[0])/2.0 + cntrPt[0]
    yMid = (parentPt[1]-cntrPt[1])/2.0 + cntrPt[1]
    createPlot.ax1.text(xMid, yMid, txtString, va="center", ha="center", rotation=30)
>>> import treePlotter 
>>> mytree =  treePlotter.retrieveTree(0)
>>> treePlotter.getNumLeafs(mytree)
3
>>> treePlotter.getTreeDepth(mytree)
2
>>> treePlotter.createPlot(mytree)

这里写图片描述

Python使用matplotlib绘制树形图可以通过以下步骤实现: 首先,需要导入matplotlib库和需要的数据。然后,创建一个新的绘图对象和一个子图对象。接着,使用annotate()函数为每个节点添加注解,并设置节点的坐标和文本。在注解中,可以设置箭头的样式、颜色和文本的格式。最后,需要显示绘图并保存图像。 下面是一个示例代码: ```python import matplotlib.pyplot as plt # 创建树形图数据 data = { &#39;A&#39;: [&#39;B&#39;, &#39;C&#39;], &#39;B&#39;: [&#39;D&#39;, &#39;E&#39;], &#39;C&#39;: [&#39;F&#39;, &#39;G&#39;] } # 创建新的绘图对象和子图对象 fig, ax = plt.subplots() # 添加节点注解 def annotate_tree(node, parent, pos, text_pos): ax.annotate(node, pos, text_pos, arrowprops=dict(arrowstyle=&#39;->&#39;, color=&#39;black&#39;), xycoords=&#39;axes fraction&#39;, textcoords=&#39;axes fraction&#39;, va=&#39;center&#39;, ha=&#39;center&#39;) if node in data: children = data[node] y_off = 1 / (len(children) + 1) for i, child in enumerate(children): annotate_tree(child, node, (pos[0], pos[1] - y_off * (i + 1)), (text_pos[0], text_pos[1] - y_off * (i + 1))) annotate_tree(&#39;A&#39;, None, (0.5, 1), (0.5, 1)) ax.axis(&#39;off&#39;) # 显示绘图 plt.show() ``` 以上代码演示了如何使用matplotlib绘制树形图。通过annotate_tree函数递归地为节点添加注解,并设置箭头的样式和节点的位置。最后,使用ax.axis(&#39;off&#39;)函数将坐标轴关闭,以显示树形图
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值