第二章介紹的k-近鄰算法可以完成很多分類任務,但是它最大的缺點就是無法給出數據內在的含義,決策樹的主要優勢在于數據形式非常容易理解。
決策樹
優點:計算復雜度不高,輸出結果易于理解,對中間值的缺失不敏感,可以處理不相關特征數據。
缺點:可能會產生過度匹配的問題
適用數據類型:數值型和標稱型
先計算給定數據集的香農熵
在CSDN的Markdown中,第一行居然不居中,簡書的是默認居中了
序號 | 不浮出水面是否可以生存 | 是否有腳蹼 | 屬于魚類 |
---|---|---|---|
1 | 1 | 1 | 1 |
2 | 1 | 1 | 1 |
3 | 1 | 0 | 0 |
3 | 0 | 1 | 0 |
3 | 0 | 1 | 0 |
from math import log
def calcShannonEnt(dataSet):
numEntries = len(dataSet)
labelCounts = {}
#為所有可能的分類創建字典
for featVec in dataSet:
currentLabel = featVec[-1]
if currentLabel not in labelCounts.keys():labelCounts[currentLabel] = 0
labelCounts[currentLabel] += 1
shannonEnt = 0.0
#計算熵
for key in labelCounts:
prob = float(labelCounts[key])/numEntries
#底數為2求對數
shannonEnt -= prob*log(prob,2)
return shannonEnt
def createDataSet():
dataSet = [[1,1,'yes'],
[1,1,'yes'],
[1,0,'no'],
[0,1,'no'],
[0,1,'no']]
labels = ['no surfacing','flippers']
return dataSet,labels
測試數據集的熵
import trees
reload(trees)
myDat,labels = trees.createDataSet()
>>> myDat
[[1, 1, 'yes'], [1, 1, 'yes'], [1, 0, 'no'], [0, 1, 'no'], [0, 1, 'no']]
>>> trees.calcShannonEnt(myDat)
0.9709505944546686
熵越高,則混合的數據也越多
增加一個測試分類來測試熵的變化:
>>> myDat[0][-1]='maybe'
>>> myDat
[[1, 1, 'maybe'], [1, 1, 'yes'], [1, 0, 'no'], [0, 1, 'no'], [0, 1, 'no']]
>>> trees.calcShannonEnt(myDat)
1.3709505944546687
下面,開始劃分數據集:
def splitDataSet(dataSet, axis, value):
retDataSet = []
for featVec in dataSet:
#將符合要求的數據集添加到列表中
if featVec[axis] == value:
reducedFeatVec = featVec[:axis]
reducedFeatVec.extend(featVec[axis+1:])
retDataSet.append(reducedFeatVec)
return retDataSet
本段代碼使用了三個輸入參數:待劃分的數據集,劃分數據集的特征,需要返回的特征的值。
然后在Python命令提示符內輸入下述命令:
>>> myDat
[[1, 1, 'yes'], [1, 1, 'yes'], [1, 0, 'no'], [0, 1, 'no'], [0, 1, 'no']]
>>> trees.splitDataSet(myDat,0,1)
[[1, 'yes'], [1, 'yes'], [0, 'no']]
>>> trees.splitDataSet(myDat,0,0)
[[1, 'no'], [1, 'no']]
>>>
接下來我們開始遍歷整個數據集,循環計算香農熵和splitDataSet()函數,找到最好的特征劃分方式。
def chooseBestFeatureToSplit(dataSet):
numFeatures = len(dataSet[0]) - 1
baseEntropy = calcShannonEnt(dataSet)#計算原始香農熵
bastInfoGain = 0.0;baseFeature = -1
for i in range(numFeatures):
featList = [example[i] for example in dataSet]
uniqueVals = set(featList)#創建分類標簽集合
newEntropy = 0.0
for value in uniqueVals:
subDataSet = splitDataSet(dataSet, i, value)
prob = len(subDataSet)/float(len(dataSet))
newEntropy += prob * calcShannonEnt(subDataSet)
infoGain = baseEntropy - newEntropy
if (infoGain > bestInfogain):
bestInfoGain = infoGain
bestFeature = i
return bestFeature
從列表中新建集合是Python語言得到列表中唯一元素的最快方法
下面開始測試上面代碼的實際輸出結果
>>> trees.chooseBestFeatureToSplit(myDat)
0
>>> myDat
[[1, 1, 'yes'], [1, 1, 'yes'], [1, 0, 'no'], [0, 1, 'no'], [0, 1, 'no']]
代碼告訴我們,第0個特征是最好的用于劃分數據集的特征
下面我們開始采用遞歸的方式處理數據集
如果數據集已經處理了所有屬性,但是類標簽依然不是唯一的,此時我們需要決定如何定義該葉子節點,在這種情況下,我們通常會采用多數表決的方法決定該葉子節點的分類
import operator
def majorityCnt(classList):
classCount = {}
for vote in classList:#統計數據字典classList每一個類標簽出現的頻率
if vote not in classCount.keys(): classCount[vote] = 0
classCount[vote] += 1
sortedClassCount = sorted(classCount.iteritems(), key=operator.itemgette(1), reverse=True)#排序
return sortedClassCount[0][0]#返回次數最多的
下面開始加入創建樹的函數代碼
def createTree(dataSet, labels):#數據集,標簽列表
classList = [example[-1] for example in dataSet]#最后一個屬性加入列表變量classList
#類別完全相同則停止劃分
if classList.count(classList[0]) == len(classList):
return classList[0]
if len(dataSet[0]) == 1:#遍歷完所有特征,返回次數最多的類別
return majorityCnt(classList)
bestFeat = chooseBestFeatureToSplit(dataSet)
bestFeatLabel = labels[bestFeat]
myTree = {bestFeatLabel:{}}
del(labels[bestFeat])
featValues = [example[bestFeat] for example in dataSet]
uniqueVals = set(featValues)
for value in uniqueVals:
subLabels = labels[:]
myTree[bestFeatLabel][value] = createTree(splitDataSet(dataSet, bestFeat, value),subLabels)
return myTree
subLabels = labels[:],這行代碼復制了類標簽,并將其存儲在新列表變量subLabels中。之所以這樣做,是因為在Python語言中,函數參數是列表類型時,參數是按照引用方式傳遞的。為了保證每次調用函數createTree()時不改變原始列表的內容,使用新變量subLabels代替原始列表。
下面是測試實際輸出結果
#trees-1.py
import trees
reload(trees)
myDat,labels = trees.createDataSet()
myTree = trees.createTree(myDat,labels)
>>> myTree
{'no surfacing': {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}}
下面開始學習使用Matplotlib畫圖
#-*- coding=utf-8 -*-
import matplotlib.pyplot as plt
decisionNode = dict(boxstyle="sawtooth",fc="0.8")
leafNode = dict(boxstyle="round4",fc="0.8")
arrow_args = dict(arrowstyle="<-")
def plotNode(nodeTxt, centerPt, parentPt, nodeType):
createPlot.ax1.annotate(nodeTxt,
xy=parentPt,
xycoords='axes fraction',
xytext=centerPt,
textcoords='axes fraction',
va="center",
ha="center",
bbox=nodeType,
arrowprops=arrow_args )
def createPlot():
fig = plt.figure(1,facecolor='white')
fig.clf()
createPlot.ax1 = plt.subplot(111,frameon=False)
plotNode("a decision node",(0.5,0.1),(0.1,0.5),decisionNode)
plotNode("a leaf node",(0.8,0.1),(0.3,0.8),leafNode)
plt.show()
>>> import treePlotter;treePlotter.createPlot()
下面開始獲取葉節點的數目和樹的層數
def getNumLeafs(myTree):
numLeafs = 0
firstStr = myTree.keys()[0]
secondDict = myTree[firstStr]
for key in secondDict.keys():
if type(secondDict[key]).__name__=='dict':
numLeafs += getNumLeafs(secondDict[key])
else: numLeafs +=1
return numLeafs
def getTreeDepth(myTree):
maxDepth = 0
firstStr = myTree.keys()[0]
secondDict = myTree[firstStr]
for key in secondDict.keys():
if type(secondDict[key]).__name__=='dict':
thisDepth = 1 + getTreeDepth(secondDict[key])
else: thisDepth = 1
if thisDepth > maxDepth: maxDepth = thisDepth
return maxDepth
def retrieveTree(i):
listOfTrees = [{'no surfacing': {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}},
{'no surfacing': {0: 'no', 1: {'flippers': {0: {'head': {0: 'no', 1: 'yes'}}, 1: 'no'}}}}
]
return listOfTrees[i]
>>> import treePlotter
>>> treePlotter.retrieveTree(1)
{'no surfacing': {0: 'no', 1: {'flippers': {0: {'head': {0: 'no', 1: 'yes'}}, 1: 'no'}}}}
>>> myTree = treePlotter.retrieveTree(0)
>>> treePlotter.getNumLeafs(myTree)
3
>>> treePlotter.getTreeDepth(myTree)
2
更新部分代碼,開始嘗試畫圖
def plotMidText(cntrPt, parentPt, txtString):#計算父節點和子節點的中間位置
xMid = (parentPt[0]-cntrPt[0])/2.0 + cntrPt[0]
yMid = (parentPt[1]-cntrPt[1])/2.0 + cntrPt[1]
createPlot.ax1.text(xMid, yMid, txtString, va="center", ha="center", rotation=30)
def plotTree(myTree, parentPt, nodeTxt):
numLeafs = getNumLeafs(myTree)
depth = getTreeDepth(myTree)
firstStr = myTree.keys()[0]
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':
plotTree(secondDict[key],cntrPt,str(key))
else:
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
并更新creaePlot()部分的代碼
def createPlot(inTree):
fig = plt.figure(1,facecolor='white')
fig.clf()
axprops = dict(xticks=[], yticks=[])
createPlot.ax1 = plt.subplot(111,frameon=False, **axprops)
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()
開始畫圖
#treePlotter-1.py
import treePlotter
myTree=treePlotter.retrieveTree(0)
treePlotter.createPlot(myTree)
接著添加字典的內容,重新繪制圖片
>>> myTree['no surfacing'][3] = 'maybe'
>>> myTree
{'no surfacing': {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}, 3: 'maybe'}}
>>> treePlotter.createPlot(myTree)
下面開始重點講如何利用決策樹執行數據分類
在執行數據分類時,需要使用決策樹以及用于構造決策樹的標簽向量。然后,程序比較測試數據與決策樹上的數值,遞歸執行該過程直到進入葉子節點;最后將測試數據定義為葉子節點所屬的類型。
#使用決策樹的分類函數
#添加到trees.py
def classify(inputTree, featLabels, testVec):
firstStr = inputTree.keys()[0]
secondDict = inputTree[firstStr]
featIndex = featLabels.index(firstStr)#將標簽字符串轉化為索引
for key in secondDict.keys():
if testVec[featIndex] == key:
if type(secondDict[key]).__name__=='dict':#遞歸遍歷
classLabel = classify(secondDict[key],featLabels,testVec)
else: classLabel = secondDict[key]
#key = testVec[featIndex]
#valueOfFeat = secondDict[key]
#if isinstance(valueOfFeat, dict):#是否是實例
# classLabel = classify(valueOfFeat, featLabels, testVec)
#else: classLabel = valueOfFeat
return classLabel
#trees-1
import trees
import treePlotter
myDat,labels = trees.createDataSet()
myTree=treePlotter.retrieveTree(0)
>>> labels
['no surfacing', 'flippers']
>>> myTree
{'no surfacing': {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}}
>>> trees.classify(myTree,labels,[1,0])
'no'
>>> trees.classify(myTree,labels,[1,1])
'yes'
下面開始在硬盤上存儲決策樹分類器
#trees.py
def storeTree(inputTree,filename):
import pickle#重點
fw = open(filename,'w')
pickle.dump(inputTree,fw)
fw.close()
def grabTree(filename):
import pickle
fr = open(filename)
return pickle.load(fr)
#tree-1.py
import trees
import treePlotter
myDat,labels = trees.createDataSet()
myTree = trees.createTree(myDat,labels)
trees.storeTree(myTree,'classifierStorage.txt')
>>> trees.grabTree('classifierStorage.txt')
{'no surfacing': {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}}
import trees
import treePlotter
myDat,labels = trees.createDataSet()
myTree = trees.createTree(myDat,labels)
fr=open('lenses.txt')
lenses=[inst.strip().split('\t') for inst in fr.readlines()]
lensesLabels=['age','prescript','astigmatic','tearRate']
lensesTree = trees.createTree(lenses,lensesLabels)
>>> treePlotter.createPlot(lensesTree)