ML-in-Action-Code-and-Note
ML-in-Action-Code-and-Note copied to clipboard
A bug need to adjust
def getNumleafs(myTree):
numLeafs =0#初始化节点数
firstSides = list(myTree.keys())#先把最广的key遍历
firstStr = firstSides[0]#取第一个key
secondDict = myTree[firstStr]#取第一个key的子字典
#=>Traceback (most recent call last):
File "/Users/admin/PycharmProjects/untitled20/机器学习/决策树的实现.py", line 317, in <module>
createPlot(myDat)
File "/Users/admin/PycharmProjects/untitled20/机器学习/决策树的实现.py", line 98, in createPlot
plotTree.totalW = float(getNumleafs(inTree))
File "/Users/admin/PycharmProjects/untitled20/机器学习/决策树的实现.py", line 18, in getNumleafs
firstSides = dict(myTree.keys())#先把最广的key遍历
AttributeError: 'list' object has no attribute 'keys'
The problem was that the PY3.5 to PY3.6 had changed the rules within the dict uses
@wheniseeyou thank you, in python3.6 it may works by changing like this:
def getNumleafs(myTree):
numLeafs =0#初始化节点数
#firstSides = list(myTree.keys())
#firstStr = firstSides[0]
#secondDict = myTree[firstStr]
#for key in secondDict.keys():
for key in myTree.values():
if type(value).__name__=='dict':
numLeafs+=getNumLeafs(value)
else: numLeafs+=1
return numLeafs
reference: https://stackoverflow.com/questions/43729468/decision-tree-str-object-has-no-attribute-keys-python3-6