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()[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 = myTree[firstStr]
plotTree.yOff = plotTree.yOff - 1.0/plotTree.totalD
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
plotTree(secondDict[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[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
def createPlot(inTree):
fig = plt.figure(1, facecolor='white')
fig.clf()
axprops = dict(xticks=[], yticks=[])
createPlot.ax1 = plt.subplot(111, frameon=False, **axprops) #no ticks
#createPlot.ax1 = plt.subplot(111, frameon=False) #ticks for demo puropses
plotTree.totalW = float(getNumLeafs(inTree))
plotTree.totalD = float(getTreeDepth(inTree))
plotTree.xOff = -0.5/plotTree.totalW; plotTree.yOff = 1.0;
plotTree(inTree, (0.5,1.0), '')
plt.show()
不理解的是类似 plotTree.totalW = float(getNumLeafs(inTree))
plotTree.totalD = float(getTreeDepth(inTree))
plotTree.xOff = -0.5/plotTree.totalW; plotTree.yOff = 1.0;
这种变量形式,原书上说这是全局变量,但是查了语法,全局变量只有两种形式,一种是用关键字global,另一种是模块,这里的有点类似模块,但是源代码里也没有模块的声明和引用,求解
3 个解决方案
#1
在线等.....................
#2
class A:
pass
a=A()
a.name='ok'
print(a.name)
def f():
pass
f.x=55
print(f.x)
----------------
函数是个对象,可以随时添加公共属性~
pass
a=A()
a.name='ok'
print(a.name)
def f():
pass
f.x=55
print(f.x)
----------------
函数是个对象,可以随时添加公共属性~
#3
看看OOP对象化编程。如果玩过JS对象化编程,联系一下也是同样的。
#1
在线等.....................
#2
class A:
pass
a=A()
a.name='ok'
print(a.name)
def f():
pass
f.x=55
print(f.x)
----------------
函数是个对象,可以随时添加公共属性~
pass
a=A()
a.name='ok'
print(a.name)
def f():
pass
f.x=55
print(f.x)
----------------
函数是个对象,可以随时添加公共属性~
#3
看看OOP对象化编程。如果玩过JS对象化编程,联系一下也是同样的。