python 实现决策树画图

文章参考自:http://blog.csdn.net/wzmsltw/article/details/51039928

# -*- coding: utf-8 -*-
"""
Created on Wed Sep 27 14:52:51 2017

@author: Administrator
"""

import matplotlib.pyplot as plt  
decisionNode=dict(boxstyle="sawtooth",fc="0.8")  
leafNode=dict(boxstyle="round4",fc="0.8")  
arrow_args=dict(arrowstyle="<-")  
  
  
#计算树的叶子节点数量  
def getNumLeafs(myTree):  
    numLeafs=0  
    firstStr=myTree.keys()[0]  
    secondDict=myTree[firstStr]  
    for key in secondDict.keys():  
        if type(secondDict[key]).__name__=='dict':  
            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  
  
#画节点  
def plotNode(nodeTxt,centerPt,parentPt,nodeType):  
    createPlot.ax1.annotate(nodeTxt,xy=parentPt,xycoords='axes fraction',xytext=centerPt,textcoords='axes fraction',va="center", ha="center",bbox=nodeType,arrowprops=arrow_args) 
      
    
  
#画箭头上的文字  
def plotMidText(cntrPt,parentPt,txtString):  
    lens=len(txtString)  
    xMid=(parentPt[0]+cntrPt[0])/2.0-lens*0.002  
    yMid=(parentPt[1]+cntrPt[1])/2.0  
    createPlot.ax1.text(xMid,yMid,txtString)  
      
def plotTree(myTree,parentPt,nodeTxt):  
    numLeafs=getNumLeafs(myTree)  
    depth=getTreeDepth(myTree)  
    firstStr=myTree.keys()[0]  
    cntrPt=(plotTree.x0ff+(1.0+float(numLeafs))/2.0/plotTree.totalW,plotTree.y0ff)  
    plotMidText(cntrPt,parentPt,nodeTxt)  
    plotNode(firstStr,cntrPt,parentPt,decisionNode)  
    secondDict=myTree[firstStr]  
    plotTree.y0ff=plotTree.y0ff-1.0/plotTree.totalD  
    for key in secondDict.keys():  
        if type(secondDict[key]).__name__=='dict':  
            plotTree(secondDict[key],cntrPt,str(key))  
        else:  
            plotTree.x0ff=plotTree.x0ff+1.0/plotTree.totalW  
            plotNode(secondDict[key],(plotTree.x0ff,plotTree.y0ff),cntrPt,leafNode)  
            plotMidText((plotTree.x0ff,plotTree.y0ff),cntrPt,str(key))  
    plotTree.y0ff=plotTree.y0ff+1.0/plotTree.totalD  
  
def createPlot(inTree):  
    fig=plt.figure(1,facecolor='white')  
    fig.clf()  
    axprops=dict(xticks=[],yticks=[])  
    createPlot.ax1=plt.subplot(111,frameon=False,**axprops)  
    plotTree.totalW=float(getNumLeafs(inTree))  
    plotTree.totalD=float(getTreeDepth(inTree))  
    plotTree.x0ff=-0.5/plotTree.totalW  
    plotTree.y0ff=1.0  
    plotTree(inTree,(0.5,1.0),'')  
    plt.show() 
###############测试代码
tree={'navel': {'even': 0L,
  'little_sinking': {'root': {'curl_up': 0L,
    'little_curl_up': {'color': {'black': {'texture': {'blur': 1L,
        'distinct': 0L,
        'little_blur': 1L}},
      'dark_green': 1L,
      'light_white': 1L}},
    'stiff': 1L}},
  'sinking': {'color': {'black': 1L, 'dark_green': 1L, 'light_white': 0L}}}}
createPlot(tree)

结果:


  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
### 回答1: 要使用Python绘制决策树,可以使用Graphviz和pydotplus这两个库。以下是一个简单的例子: ```python from sklearn.datasets import load_iris from sklearn import tree import graphviz import pydotplus # 加载数据集 iris = load_iris() # 创建决策树模型 clf = tree.DecisionTreeClassifier() # 拟合模型 clf = clf.fit(iris.data, iris.target) # 绘制决策树 dot_data = tree.export_graphviz(clf, out_file=None, feature_names=iris.feature_names, class_names=iris.target_names, filled=True, rounded=True, special_characters=True) graph = pydotplus.graph_from_dot_data(dot_data) graphviz.Source(graph.to_string()) ``` 这段代码会输出一个决策树图像。如果你想将图像保存到文件中,可以使用以下代码: ```python graph.write_png('iris.png') ``` 这将把决策树保存为PNG格式的文件。 ### 回答2: 在Python中,可以使用`scikit-learn`库中的`DecisionTreeClassifier`和`DecisionTreeRegressor`类来构建决策树模型,并使用`Graphviz`库中的`export_graphviz`函数将决策树结构可视化。 首先,需要安装`scikit-learn`和`Graphviz`库。可以使用以下命令安装它们: ```python pip install scikit-learn pip install graphviz ``` 接下来,导入相关库: ```python from sklearn.tree import DecisionTreeClassifier, export_graphviz import graphviz ``` 然后,构建特征矩阵`X`和目标变量`y`,并创建决策树模型: ```python X = [[...], [...], ...] # 特征矩阵 y = [1, 0, 1, 0, ...] # 目标变量 clf = DecisionTreeClassifier() # 创建决策树分类器 clf.fit(X, y) # 训练决策树模型 ``` 训练完成后,可以使用`export_graphviz`函数导出决策树的结构: ```python dot_data = export_graphviz(clf, out_file=None) graph = graphviz.Source(dot_data) graph.render("decision_tree") # 将决策树保存为decision_tree.pdf或decision_tree.png文件 ``` 以上代码将生成一个决策树的.dot文件,并使用`Graphviz`库将其转换为可视化图形。可以使用`.render()`方法保存该图形为.pdf或.png格式文件。 最后,我们可以通过`graph`对象的`.view()`方法在浏览器中查看决策树图形: ```python graph.view() ``` 这样,我们就成功地用Python画出了决策树的可视化图形。 ### 回答3: Python中可以使用多个库来画决策树图,其中比较常用的有`graphviz`库和`matplotlib`库。 使用`graphviz`库可以在Python中创建和渲染决策树图。该库需要先安装`graphviz`软件,并将其添加到系统的环境变量中。在Python中,可以使用`sklearn`库来构建决策树模型,然后使用`export_graphviz`函数将决策树导出为`.dot`文件。接下来,可以使用`graphviz`库提供的`Source`函数读取`.dot`文件,并通过调用`view`方法显示决策树图形界面。 另一种常见的方法是使用`matplotlib`库绘制决策树图。首先,需要使用`sklearn`库中的`export_graphviz`函数将决策树导出为`.dot`文件。然后,可以使用`pydot`库读取该文件,并通过调用`graph_from_dot_data`函数创建一个`pydot.Dot`对象。最后,可以通过指定不同节点的样式和连接关系来绘制决策树图,最终使用`matplotlib`库将其显示出来。 总结来说,使用Python决策树图主要涉及到以下几个步骤:安装相关的库(如`sklearn`、`graphviz`、`pydot`、`matplotlib`等),构建决策树模型,将决策树导出为`.dot`文件,使用`graphviz`库或`matplotlib`库将`.dot`文件转换为图形界面并显示出来。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值