機器學習實戰決策樹

2021-08-09 22:25:43 字數 1100 閱讀 4018

這幾天一直在學習機器學習實戰python**實現,在程式清單的3-6  獲取及誒單數程式,書上的程式是這樣的

def 

getnumleafs(mytree):

numleafs = 0.0

firststr=list(dict.keys(mytree))[0]

seconddict=mytree[firststr]

print(seconddict)

print(seconddict.keys())

for key in seconddict.keys():

print(seconddict[key])

if type(seconddict[key])=='dict':

numleafs+=getnumleafs(seconddict[key])

else:

numleafs+=1

print(numleafs)

return numleafs

有的地方為了測試我自己加了幾段**,執行結果如下:}}

dict_keys([0, 1]) no

1.0 }

2.02.0

由此看出,在子樹沒有執行進去,輸出結果應該是3,但是這裡是2,顯然不對,於是我自己編寫乙個函式,比書上簡潔執行結果是對的:

程式如下:

def 

getnumleafs(mytree):

numleafs=0.0

for feat in mytree.keys():

if type(mytree[feat]).__name__=='dict':

numleafs+=getnumleafs(mytree[feat])

else:numleafs+=1

return numleafs

mytree = }}}

a = getnumleafs(mytree)

print(a)

print(mytree.keys())

執行結果如下:
3.0

dict_keys(['no su***cing'])

符合預知的結果:

機器學習實戰 決策樹

決策樹 2 python語言在函式中傳遞的是列表的引用,在函式內部對列表物件的修改,將會影響該列表物件的整個生存週期。為了消除這個不良影響,我們需要在函式的開始宣告乙個新列表物件。在本節中,指的是在劃分資料集函式中,傳遞的引數dataset列表的引用,為了不影響dataset我們重新宣告了乙個ret...

機器學習實戰 決策樹

class sklearn.tree.decisiontreeclassifier criterion gini splitter best max depth none,min samples split 2,min samples leaf 1,min weight fraction leaf ...

機器學習實戰 決策樹

def calcshannonent dataset numentries len dataset labelcounts for featvec in dataset currentlabel featvec 1 if currentlabel not in labelcounts.keys la...