機器學習筆記(三)——決策樹

優點:計算複雜度不高,輸出結果易於理解,對中間值的缺失不敏感,可以處理不相關特徵數據。

缺點:可能會產生過度匹配問題

使用數據類型:數值型和標稱型

 

決策樹的一般流程

(1)收集數據:可以使用任何方法;

(2)準備數據:樹構造算法只適用於標稱型數據,因此數值型數據必須離散化;

(3)分析數據:可以使用任何方法,構造樹完成之後,我們應該檢查圖形是否符合預期;

(4)訓練算法:構造樹的數據結構;

(5)測試算法:使用經驗樹計算錯誤率;

(6)使用算法:此步驟可以適用於任何監督學習算法,而使用決策樹可以更好地理解數據的內在含義。

        

1中給出5個海洋動物的數據,特徵包括:不浮出水面是否可以生存,以及是否有腳蹼。我們可以將這些動物分爲兩類:魚類和非魚類。 下面將以這個例子學習決策樹


如何劃分數據集?

 

    一些決策樹採用二分法劃分數據,本文采用ID3算法劃分數據集。

    劃分數據集的大原則是:將無序的數據變得更加有序。

 

    如何評測哪種數據劃分方式最好?

        在劃分數據集之前和之後信息發生的變化稱爲信息增益(information gain,知道如何計算信息增益,我們就可以計算每個特徵值劃分數據集獲得的信息增益,獲得信息增益最高的特徵就是最好的選擇。

    如何計算信息增益?

        集合信息的度量方式稱爲香農熵或簡稱熵(entropy

 

        計算熵

        

        其中p(xi)是選擇該分類的概率,n爲分類的數目。

        使用Python計算信息熵: 

# coding=utf-8
from math import log
import operator

# 計算給定數據集合的香農熵
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
		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

以上代碼中,calcShannonEnt() 計算熵,createDataSet() 給出一組鑑定數據

 

執行命令查看結果:

    

    熵越高,則混合的數據也越多。

    我們可以在數據集中添加更多的分類,來觀察熵是如何變化的。這裏增加第三個名爲maybe的分類,測試熵的變化:

    


劃分數據集

        對每個特徵劃分數據集的結果計算一次信息熵,然後判斷按照哪個特徵劃分數據集是最好的劃分方法。

        在trees.py中加入如下代碼:

# 按照給定特徵劃分數據集	
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

	
# 選擇最好的數據集劃分方式
def chooseBestFeatureToSplit(dataSet):
	# 每行數據個數-1
	numFeatures = len(dataSet[0]) - 1
	# 計算數據集合的熵
	baseEntropy = calcShannonEnt(dataSet)
	bestInfoGain = 0.0
	bestFeature = -1
	# 遍歷每一列
	for i in range(numFeatures):
		# 提取dateSet數據集中的第i列是所有值
		featList = [example[i] for example in dataSet]
		uniqueVals = set(featList)
		newEntropy = 0.0
		for value in uniqueVals:
			# 按照value劃分數據集,即找出第i列中是value的所有數據
			subDataSet = splitDataSet(dataSet, i, value)
			# 這些數據佔整個數據集的比例prob
			prob = len(subDataSet) / float(len(dataSet))
			# 對每種劃分方式計算信息熵,再乘以prob, 然後把所有信息熵相加
			newEntropy += prob * calcShannonEnt(subDataSet)
		infoGain = baseEntropy - newEntropy
		# 比較所有特徵中的信息熵增益,返回最好特徵劃分的索引值
		if(infoGain > bestInfoGain):
			bestInfoGain = infoGain
			bestFeature = i
	return bestFeature

執行命令查看結果:

    

代碼運行結果告訴我們,第0個特徵是最好的用於劃分數據集的特徵。

到此,我們學習瞭如何度量數據集的信息熵,如何有效地劃分數據集,下面將介紹如何將這些函數功能放在一起,構建決策樹。


遞歸構建決策樹

 

工作原理:

1)得到原始數據集;

2)然後基於最好的屬性值劃分數據集,由於特徵值可能多於兩個,因此可能存在大於兩個分支的數據劃分;

3)第一次劃分之後,數據將被向下傳遞到樹分支的下一個節點,在這個節點上,我們可以再次劃分數據。

 

遞歸結束的條件:

程序遍歷完所有劃分數據集的屬性,或者每個分支下的所有實例都具有相同的分類。如下圖

    如果數據處理了所有的屬性,但是類標籤依然不是唯一的,此時我們該如何定義該葉子節點?

    在這種情況下,我們通常採用多數表決的方法決定葉子節點的分類。代碼實現如下:

    在trees.py文件中加入如下代碼:

def majorityCnt(classList):
	classCount = {}
	for vote in classList:
		if vote not in classCount.keys():
			classCount[vote] = 0
		classCount[vote] += 1
	# 按照dict中value的值從大到小排序
	sortedClassCount = sorted(classCount.iteritems(), key = operator.itemgetter(1), reverse=True)
	# 返回出現次數最多的分類名稱
	return sortedClassCount[0][0]

下面是創建樹的代碼:

def createTree(dataSet, labels):
	classList = [example[-1] for example in dataSet]
	# 類別完全相同則停止繼續劃分
	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:{}}
	# 刪除標籤列表中序號爲bestFeat的標籤
	del(labels[bestFeat])	
	# 得到列表包含的所有屬性值
	featValues = [example[bestFeat] for example in dataSet]
	uniqueVals = set(featValues)
	for value in uniqueVals:
		subLabels = labels[:]
		myTree[bestFeatLabel][value] = createDataSet(splitDataSet(dataSet, bestFeat, value), subLabels)
	return myTree

執行命令查看結果:

    


繪製樹形圖

 

決策樹的主要優點是直觀易於理解,如果不能將其直觀地顯示出來,就無法發揮其優勢。下面將使用Matplotlib註解繪製樹形圖

新建treePlotter.py文件,在此文件中加入如下代碼:

# 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()
'''

# 獲取葉子節點的數目	
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]

# 在父子節點間填充文本信息
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)
	
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
	
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()

執行命令查看結果:

    

運行結果:

    


測試算法:使用決策樹執行分類


依靠訓練數據構造決策樹之後,我們可以將它用於實際數據的分類中。

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]
	return classLabel

執行命令查看結果:

    


決策樹的存儲


現在我們已經創建了使用決策樹的分類器,但每次使用分類器時,必須重新構造決策樹,這將會耗費大量的時間。因此,爲了節省時間,最好能夠在每次執行分類時調用已經構造好的決策樹。

# 使用Pickle模塊存儲決策樹
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)
    

通過上面的代碼,我們可以將分類器存儲在硬盤上,而不用每次對數據分類時重新學習一遍,
這也是決策樹的優點之一,像第2章介紹的k-近鄰算法就無法持久化分類器。


實例:使用決策樹預測隱形眼鏡類型

(1)收集數據:提供的文本文件

(2)準備數據:解析tab鍵分隔的數據行

(3)分析數據:快速檢查數據,確保正確地解析數據內容,使用createPlot()函數繪製最終的樹形圖

(4)訓練算法:使用createTree()函數

(5)測試算法:編寫測試函數驗證決策樹可以正確分類給定的數據實例

(6)使用算法:存儲樹的數據結構,以便下次使用時無需重新構造樹

    

    




申明:本文爲本人學習中所記之筆記,歡迎各位讀者前來交流學習心得,如有批評建議請在下方評論處留言,轉載請註明出處:http://blog.csdn.net/jay_xio/article/details/44516623

作者:Jay_Xio








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