機器學習之決策樹二-C4.5

                                決策樹之系列二—C4.5

                                                本文系作者原創,轉載請註明出處:https://www.cnblogs.com/further-further-further/p/9435712.html 

ID3算法缺點

它一般會優先選擇有較多屬性值的Feature,因爲屬性值多的特徵會有相對較大的信息增益,信息增益反映的是,在給定一個條件以後,不確定性減少的程度,

這必然是分得越細的數據集確定性更高,也就是條件熵越小,信息增益越大。爲了解決這個問題,C4.5就應運而生,它採用信息增益率來作爲選擇分支的準則。

C4.5算法原理

信息增益率定義爲:

              

其中,分子爲信息增益(信息增益計算可參考上一節ID3的算法原理),分母爲屬性X的熵。

需要注意的是,增益率準則對可取值數目較少的屬性有所偏好。

所以一般這樣選取劃分屬性:選擇增益率最高的特徵列作爲劃分屬性的依據。

代碼實現

與ID3代碼實現不同的是:只改變計算香農熵的函數calcShannonEnt,以及選擇最優特徵索引函數chooseBestFeatureToSplit,具體代碼如下:

  1 # -*- coding: utf-8 -*-
  2 """
  3 Created on Thu Aug  2 17:09:34 2018
  4 決策樹ID3,C4.5的實現
  5 @author: weixw
  6 """
  7 from math import log
  8 import operator
  9 #原始數據
 10 def createDataSet():
 11     dataSet = [[1, 1, 'yes'],
 12                [1, 1, 'yes'],
 13                [1, 0, 'no'],
 14                [0, 1, 'no'],
 15                [0, 1, 'no']]
 16     labels = ['no surfacing','flippers']   
 17     return dataSet, labels
 18 
 19 #多數表決器
 20 #列中相同值數量最多爲結果
 21 def majorityCnt(classList):
 22     classCounts = {}
 23     for value in classList:
 24         if(value not in classCounts.keys()):
 25             classCounts[value] = 0
 26         classCounts[value] +=1
 27     sortedClassCount = sorted(classCounts.iteritems(),key = operator.itemgetter(1),reverse =True)
 28     return sortedClassCount[0][0]
 29         
 30     
 31 #劃分數據集
 32 #dataSet:原始數據集
 33 #axis:進行分割的指定列索引
 34 #value:指定列中的值
 35 def splitDataSet(dataSet,axis,value):
 36     retDataSet= []
 37     for featDataVal in dataSet:
 38         if featDataVal[axis] == value:
 39             #下面兩行去除某一項指定列的值,很巧妙有沒有
 40             reducedFeatVal = featDataVal[:axis]
 41             reducedFeatVal.extend(featDataVal[axis+1:])
 42             retDataSet.append(reducedFeatVal)
 43     return retDataSet
 44 
 45 #計算香農熵
 46 #columnIndex = -1表示獲取數據集每一項的最後一列的標籤值
 47 #其他表示獲取特徵列
 48 def calcShannonEnt(columnIndex, dataSet):
 49     #數據集總項數
 50     numEntries = len(dataSet)
 51     #標籤計數對象初始化
 52     labelCounts = {}
 53     for featDataVal in dataSet:
 54         #獲取數據集每一項的最後一列的標籤值
 55         currentLabel = featDataVal[columnIndex]
 56         #如果當前標籤不在標籤存儲對象裏,則初始化,然後計數
 57         if currentLabel not in labelCounts.keys():
 58             labelCounts[currentLabel] = 0
 59         labelCounts[currentLabel] += 1
 60     #熵初始化
 61     shannonEnt = 0.0
 62     #遍歷標籤對象,求概率,計算熵
 63     for key in labelCounts.keys():
 64         prop = labelCounts[key]/float(numEntries)
 65         shannonEnt -= prop*log(prop,2)
 66     return shannonEnt
 67 
 68 
 69 #通過信息增益,選出最優特徵列索引(ID3)
 70 def chooseBestFeatureToSplit(dataSet):
 71     #計算特徵個數,dataSet最後一列是標籤屬性,不是特徵量
 72     numFeatures = len(dataSet[0])-1
 73     #計算初始數據香農熵
 74     baseEntropy = calcShannonEnt(-1, dataSet)
 75     #初始化信息增益,最優劃分特徵列索引
 76     bestInfoGain = 0.0
 77     bestFeatureIndex = -1
 78     for i in range(numFeatures):
 79         #獲取每一列數據
 80         featList = [example[i] for example in dataSet]
 81         #將每一列數據去重
 82         uniqueVals = set(featList)
 83         newEntropy = 0.0
 84         for value in uniqueVals:
 85             subDataSet = splitDataSet(dataSet,i,value)
 86             #計算條件概率
 87             prob = len(subDataSet)/float(len(dataSet))
 88             #計算條件熵
 89             newEntropy +=prob*calcShannonEnt(-1, subDataSet)
 90         #計算信息增益
 91         infoGain = baseEntropy - newEntropy
 92         if(infoGain > bestInfoGain):
 93             bestInfoGain = infoGain
 94             bestFeatureIndex = i
 95     return bestFeatureIndex
 96 
 97 #通過信息增益率,選出最優特徵列索引(C4.5)
 98 def chooseBestFeatureToSplitOfFurther(dataSet):
 99     #計算特徵個數,dataSet最後一列是標籤屬性,不是特徵量
100     numFeatures = len(dataSet[0])-1
101     #計算初始數據香農熵H(Y)
102     baseEntropy = calcShannonEnt(-1, dataSet)
103     #初始化信息增益,最優劃分特徵列索引
104     bestInfoGainRatio = 0.0
105     bestFeatureIndex = -1
106     for i in range(numFeatures):
107         #獲取每一特徵列香農熵H(X)
108         featEntropy = calcShannonEnt(i, dataSet)
109         #獲取每一列數據
110         featList = [example[i] for example in dataSet]
111         #將每一列數據去重
112         uniqueVals = set(featList)
113         newEntropy = 0.0
114         for value in uniqueVals:
115             subDataSet = splitDataSet(dataSet,i,value)
116             #計算條件概率
117             prob = len(subDataSet)/float(len(dataSet))
118             #計算條件熵
119             newEntropy +=prob*calcShannonEnt(-1, subDataSet)
120         #計算信息增益
121         infoGain = baseEntropy - newEntropy
122         #計算信息增益率
123         infoGainRatio = infoGain/float(featEntropy)
124         if(infoGainRatio > bestInfoGainRatio):
125             bestInfoGainRatio = infoGainRatio
126             bestFeatureIndex = i
127     return bestFeatureIndex
128         
129 #決策樹創建
130 def createTree(dataSet,labels):
131     #獲取標籤屬性,dataSet最後一列,區別於labels標籤名稱
132     classList = [example[-1] for example in dataSet]
133     #樹極端終止條件判斷
134     #標籤屬性值全部相同,返回標籤屬性第一項值
135     if classList.count(classList[0]) == len(classList):
136         return classList[0]
137     #沒有特徵,只有標籤列(1列)
138     if len(dataSet[0]) == 1:
139         #返回實例數最大的類
140         return majorityCnt(classList)
141 #    #獲取最優特徵列索引ID3
142 #    bestFeatureIndex = chooseBestFeatureToSplit(dataSet)
143     #獲取最優特徵列索引C4.5
144     bestFeatureIndex = chooseBestFeatureToSplitOfFurther(dataSet)
145     #獲取最優索引對應的標籤名稱
146     bestFeatureLabel = labels[bestFeatureIndex]
147     #創建根節點
148     myTree = {bestFeatureLabel:{}}
149     #去除最優索引對應的標籤名,使labels標籤能正確遍歷
150     del(labels[bestFeatureIndex])
151     #獲取最優列
152     bestFeature = [example[bestFeatureIndex] for example in dataSet]
153     uniquesVals = set(bestFeature)
154     for value in uniquesVals:
155         #子標籤名稱集合
156         subLabels = labels[:]
157         #遞歸
158         myTree[bestFeatureLabel][value] = createTree(splitDataSet(dataSet,bestFeatureIndex,value),subLabels)
159     return myTree
160 
161 #獲取分類結果
162 #inputTree:決策樹字典
163 #featLabels:標籤列表
164 #testVec:測試向量  例如:簡單實例下某一路徑 [1,1]  => yes(樹幹值組合,從根結點到葉子節點)
165 def classify(inputTree,featLabels,testVec):
166     #獲取根結點名稱,將dict轉化爲list
167     firstSide = list(inputTree.keys())
168     #根結點名稱String類型
169     firstStr = firstSide[0]
170     #獲取根結點對應的子節點
171     secondDict = inputTree[firstStr]
172     #獲取根結點名稱在標籤列表中對應的索引
173     featIndex = featLabels.index(firstStr)
174     #由索引獲取向量表中的對應值
175     key = testVec[featIndex]
176     #獲取樹幹向量後的對象
177     valueOfFeat = secondDict[key]
178     #判斷是子結點還是葉子節點:子結點就回調分類函數,葉子結點就是分類結果
179     #if type(valueOfFeat).__name__=='dict': 等價 if isinstance(valueOfFeat, dict):
180     if isinstance(valueOfFeat, dict):
181         classLabel = classify(valueOfFeat,featLabels,testVec)
182     else:
183         classLabel = valueOfFeat
184     return classLabel
185 
186 
187 #將決策樹分類器存儲在磁盤中,filename一般保存爲txt格式
188 def storeTree(inputTree,filename):
189     import pickle
190     fw = open(filename,'wb+')
191     pickle.dump(inputTree,fw)
192     fw.close()
193 #將瓷盤中的對象加載出來,這裏的filename就是上面函數中的txt文件    
194 def grabTree(filename):
195     import pickle
196     fr = open(filename,'rb')
197     return pickle.load(fr)
198     
199     
200  
決策樹算法
  1 '''
  2 Created on Oct 14, 2010
  3 
  4 @author: Peter Harrington
  5 '''
  6 import matplotlib.pyplot as plt
  7 
  8 decisionNode = dict(boxstyle="sawtooth", fc="0.8")
  9 leafNode = dict(boxstyle="round4", fc="0.8")
 10 arrow_args = dict(arrowstyle="<-")
 11 
 12 #獲取樹的葉子節點
 13 def getNumLeafs(myTree):
 14     numLeafs = 0
 15     #dict轉化爲list
 16     firstSides = list(myTree.keys())
 17     firstStr = firstSides[0]
 18     secondDict = myTree[firstStr]
 19     for key in secondDict.keys():
 20         #判斷是否是葉子節點(通過類型判斷,子類不存在,則類型爲str;子類存在,則爲dict)
 21         if type(secondDict[key]).__name__=='dict':#test to see if the nodes are dictonaires, if not they are leaf nodes
 22             numLeafs += getNumLeafs(secondDict[key])
 23         else:   numLeafs +=1
 24     return numLeafs
 25 
 26 #獲取樹的層數
 27 def getTreeDepth(myTree):
 28     maxDepth = 0
 29     #dict轉化爲list
 30     firstSides = list(myTree.keys())
 31     firstStr = firstSides[0]
 32     secondDict = myTree[firstStr]
 33     for key in secondDict.keys():
 34         if type(secondDict[key]).__name__=='dict':#test to see if the nodes are dictonaires, if not they are leaf nodes
 35             thisDepth = 1 + getTreeDepth(secondDict[key])
 36         else:   thisDepth = 1
 37         if thisDepth > maxDepth: maxDepth = thisDepth
 38     return maxDepth
 39 
 40 def plotNode(nodeTxt, centerPt, parentPt, nodeType):
 41     createPlot.ax1.annotate(nodeTxt, xy=parentPt,  xycoords='axes fraction',
 42              xytext=centerPt, textcoords='axes fraction',
 43              va="center", ha="center", bbox=nodeType, arrowprops=arrow_args )
 44     
 45 def plotMidText(cntrPt, parentPt, txtString):
 46     xMid = (parentPt[0]-cntrPt[0])/2.0 + cntrPt[0]
 47     yMid = (parentPt[1]-cntrPt[1])/2.0 + cntrPt[1]
 48     createPlot.ax1.text(xMid, yMid, txtString, va="center", ha="center", rotation=30)
 49 
 50 def plotTree(myTree, parentPt, nodeTxt):#if the first key tells you what feat was split on
 51     numLeafs = getNumLeafs(myTree)  #this determines the x width of this tree
 52     depth = getTreeDepth(myTree)
 53     firstSides = list(myTree.keys())
 54     firstStr = firstSides[0] #the text label for this node should be this         
 55     cntrPt = (plotTree.xOff + (1.0 + float(numLeafs))/2.0/plotTree.totalW, plotTree.yOff)
 56     plotMidText(cntrPt, parentPt, nodeTxt)
 57     plotNode(firstStr, cntrPt, parentPt, decisionNode)
 58     secondDict = myTree[firstStr]
 59     plotTree.yOff = plotTree.yOff - 1.0/plotTree.totalD
 60     for key in secondDict.keys():
 61         if type(secondDict[key]).__name__=='dict':#test to see if the nodes are dictonaires, if not they are leaf nodes   
 62             plotTree(secondDict[key],cntrPt,str(key))        #recursion
 63         else:   #it's a leaf node print the leaf node
 64             plotTree.xOff = plotTree.xOff + 1.0/plotTree.totalW
 65             plotNode(secondDict[key], (plotTree.xOff, plotTree.yOff), cntrPt, leafNode)
 66             plotMidText((plotTree.xOff, plotTree.yOff), cntrPt, str(key))
 67     plotTree.yOff = plotTree.yOff + 1.0/plotTree.totalD
 68 #if you do get a dictonary you know it's a tree, and the first element will be another dict
 69 #繪製決策樹
 70 def createPlot(inTree):
 71     fig = plt.figure(1, facecolor='white')
 72     fig.clf()
 73     axprops = dict(xticks=[], yticks=[])
 74     createPlot.ax1 = plt.subplot(111, frameon=False, **axprops)    #no ticks
 75     #createPlot.ax1 = plt.subplot(111, frameon=False) #ticks for demo puropses 
 76     plotTree.totalW = float(getNumLeafs(inTree))
 77     plotTree.totalD = float(getTreeDepth(inTree))
 78     plotTree.xOff = -0.5/plotTree.totalW; plotTree.yOff = 1.0;
 79     plotTree(inTree, (0.5,1.0), '')
 80     plt.show()
 81 
 82 #繪製樹的根節點和葉子節點(根節點形狀:長方形,葉子節點:橢圓形)
 83 #def createPlot():
 84 #    fig = plt.figure(1, facecolor='white')
 85 #    fig.clf()
 86 #    createPlot.ax1 = plt.subplot(111, frameon=False) #ticks for demo puropses 
 87 #    plotNode('a decision node', (0.5, 0.1), (0.1, 0.5), decisionNode)
 88 #    plotNode('a leaf node', (0.8, 0.1), (0.3, 0.8), leafNode)
 89 #    plt.show()
 90 
 91 def retrieveTree(i):
 92     listOfTrees =[{'no surfacing': {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}},
 93                   {'no surfacing': {0: 'no', 1: {'flippers': {0: {'head': {0: 'no', 1: 'yes'}}, 1: 'no'}}}}
 94                   ]
 95     return listOfTrees[i]
 96 
 97 #thisTree = retrieveTree(0)
 98 #createPlot(thisTree)
 99 #createPlot() 
100 #myTree = retrieveTree(0)
101 #numLeafs =getNumLeafs(myTree)
102 #treeDepth =getTreeDepth(myTree)
103 #print(u"葉子節點數目:%d"% numLeafs)
104 #print(u"樹深度:%d"%treeDepth)
繪製決策樹
 1 # -*- coding: utf-8 -*-
 2 """
 3 Created on Fri Aug  3 19:52:10 2018
 4 
 5 @author: weixw
 6 """
 7 import myTrees as mt
 8 import treePlotter as tp
 9 #測試
10 dataSet, labels = mt.createDataSet()
11 #copy函數:新開闢一塊內存,然後將list的所有值複製到新開闢的內存中
12 labels1 = labels.copy()
13 #createTree函數中將labels1的值改變了,所以在分類測試時不能用labels1
14 myTree = mt.createTree(dataSet,labels1)
15 #保存樹到本地
16 mt.storeTree(myTree,'myTree.txt')
17 #在本地磁盤獲取樹
18 myTree = mt.grabTree('myTree.txt')
19 print(u"採用C4.5算法的決策樹結果")
20 print (u"決策樹結構:%s"%myTree)
21 #繪製決策樹
22 print(u"繪製決策樹:")
23 tp.createPlot(myTree)
24 numLeafs =tp.getNumLeafs(myTree)
25 treeDepth =tp.getTreeDepth(myTree)
26 print(u"葉子節點數目:%d"% numLeafs)
27 print(u"樹深度:%d"%treeDepth)
28 #測試分類 簡單樣本數據3列
29 labelResult =mt.classify(myTree,labels,[1,1])
30 print(u"[1,1] 測試結果爲:%s"%labelResult)
31 labelResult =mt.classify(myTree,labels,[1,0])
32 print(u"[1,0] 測試結果爲:%s"%labelResult)
測試

 

運行結果

 

               

 

不要讓懶惰佔據你的大腦,不要讓妥協拖垮你的人生。青春就是一張票,能不能趕上時代的快車,你的步伐掌握在你的腳下。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章