stonycat / ML-in-Action-Code-and-Note

:chart_with_upwards_trend:Machine Learning code in Python3.x. (机器学习实战 py3代码整理)Some notes about the practices:(for reference only)
http://blog.csdn.net/sinat_17196995
270 stars 176 forks source link

A bug need to adjust #1

Open wheniseeyou opened 7 years ago

wheniseeyou commented 7 years ago
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

stonycat commented 7 years ago

@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