python3.x版本 机器学习实战《Machine Learing in Action》——第三章python中绘制决策树代码

python3.x版本下,在用example_dict.keys()或者example_dict.values()取出字典中对应的键值时,取出的值总是会带有前缀。

python2.x版本的不存在这个问题,可以直接使用书中的代码

以下是python3.x版本代码:

def plotTree(myTree, parentPt, nodeTxt):#if the first key tells you what feat was split on
    numLeafs = getNumLeafs(myTree)  #this determines the x width of this tree
    depth = getTreeDepth(myTree)
    firstStr = myTree.keys()     #the text label for this node should be this
    cntrPt = (plotTree.xOff + (1.0 + float(numLeafs))/2.0/plotTree.totalW, plotTree.yOff)
    plotMidText(cntrPt, parentPt, nodeTxt)
    plotNode(firstStr, cntrPt, parentPt, decisionNode)
    secondDict = list(myTree.values())
    plotTree.yOff = plotTree.yOff - 1.0/plotTree.totalD
    for key in range(len(secondDict[0])):
        if type(secondDict[0][key]).__name__=='dict':#test to see if the nodes are dictonaires, if not they are leaf nodes   
            plotTree(secondDict[0][key],cntrPt,str(key))        #recursion
        else:   #it's a leaf node print the leaf node
            plotTree.xOff = plotTree.xOff + 1.0/plotTree.totalW
            plotNode(secondDict[0][key], (plotTree.xOff, plotTree.yOff), cntrPt, leafNode)
            plotMidText((plotTree.xOff, plotTree.yOff), cntrPt, str(key))
    plotTree.yOff = plotTree.yOff + 1.0/plotTree.totalD
#if you do get a dictonary you know it's a tree, and the first element will be another dict

对不起,各位看官,上面的代码有点投机取巧了
由于字典的key正好是0,1,所以可以secondDict[0][key]这样索引
下面我将进行修改,使得代码普适性更好

def plotTree(myTree, parentPt, nodeTxt):#if the first key tells you what feat was split on
    numLeafs = getNumLeafs(myTree)  #this determines the x width of this tree
    depth = getTreeDepth(myTree)
    firstStr = list(myTree.keys())[0]     #the text label for this node should be this
    cntrPt = (plotTree.xOff + (1.0 + float(numLeafs))/2.0/plotTree.totalW, plotTree.yOff)
    plotMidText(cntrPt, parentPt, nodeTxt)
    plotNode(firstStr, cntrPt, parentPt, decisionNode)
    secondDict = list(myTree.values())[0]
    xinkeys=list(secondDict.keys())
    plotTree.yOff = plotTree.yOff - 1.0/plotTree.totalD
    for key in range(len(secondDict)):
        if type(secondDict[xinkeys[key]]).__name__=='dict':#test to see if the nodes are dictonaires, if not they are leaf nodes   
            plotTree(secondDict[xinkeys[key]],cntrPt,str(key))        #recursion
        else:   #it's a leaf node print the leaf node
            plotTree.xOff = plotTree.xOff + 1.0/plotTree.totalW
            plotNode(secondDict[xinkeys[key]], (plotTree.xOff, plotTree.yOff), cntrPt, leafNode)
            plotMidText((plotTree.xOff, plotTree.yOff), cntrPt, str(key))
    plotTree.yOff = plotTree.yOff + 1.0/plotTree.totalD
#if you do get a dictonary you know it's a tree, and the first element will be another dict

猜你喜欢

转载自blog.csdn.net/weixin_48622537/article/details/113099472
今日推荐