今天开始学习第三章决策树。
前面对决策树的讲解我就不写了,书上写的都很清楚,就是根据特征的不同逐步的对数据进行分类,形状像一个倒立的树。决策树算法比kNN的算法复杂度要低,理解起来也有一定难度。
每一组数据都有自己的熵,数据要整齐,熵越低。也就是说属于同一类的数据熵低,越混合的数据熵越高。计算数据集的熵代码如下:
def calcShannonEnt(dataSet):
numEntries = len(dataSet)#数据集的行
labelCounts = {}
for featVec in dataSet: #the the number of unique elements and their occurance
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) #log base 2
return shannonEnt
就是根据一个特征把数据进行划分。代码如下:
def splitDataSet(dataSet,axis,value):
retDataSet = []
for featVec in dataSet:
if featVec[axis] == value:
reducedFeatVec = featVec[:axis]#axis = 0时 这个列表是空的
reducedFeatVec.extend(featVec[axis + 1:])
retDataSet.append(reducedFeatVec)
return retDataSet
append,和extend这两个函数很有意思。
结果如下:
>>> import trees
>>> myDat,labels = trees.createDataSet()
>>> 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']]
但是实际操作中我们不能总能人工输入分类依据的特征。我们需要机器根据数据的特征自己判断最佳的分类特征。代码如下:
def chooseBestFeatureToSplit(dataSet):
numFeatures = len(dataSet[0]) - 1 #列减一
baseEntropy = calcShannonEnt(dataSet)
bestInfoGain = 0.0; bestFeature = -1
for i in range(numFeatures): # 012遍历数据集
featList = [example[i] for example in dataSet]#create a list of all the examples of this feature全部数据组的第i个数据,
uniqueVals = set(featList) #数据组的集,即{0,1}。{yes,no}
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 #calculate the info gain; ie reduction in entropy熵越低越好。
if (infoGain > bestInfoGain): #compare this to the best gain so far
bestInfoGain = infoGain #if better than current best, set to best
bestFeature = i
return bestFeature #returns an integer
结果如下:
>>> import trees
>>> myDat,labels = trees.createDataSet()
>>> trees.chooseBestFeatureToSplit(myDat)
0
书中的内容还是比较好理解的,树的建立理论也写得很详细,主要是代码比较难懂,因为python的代码很简洁,所以看起来也就更难一些。
创建树的函数代码:
def majorityCnt(classList):
classCount={}
for vote in classList:
if vote not in classCount.keys(): classCount[vote] = 0
classCount[vote] += 1
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]#stop splitting when all of the classes are equal
if len(dataSet[0]) == 1: #stop splitting when there are no more features in dataSet
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[:] #copy all of labels, so trees don't mess up existing labels
myTree[bestFeatLabel][value] = createTree(splitDataSet(dataSet, bestFeat, value),subLabels)
return myTree
首先这是一个递归函数,就是函数自己不停的调用自己,当遇到结束情况时在一步步返回。
if classList.count(classList[0]) == len(classList):
return classList[0]#stop splitting when all of the classes are equal
类的数据都是一样的时候
if len(dataSet[0]) == 1: #stop splitting when there are no more features in dataSet
return majorityCnt(classList)
只有一个数据的时候
myTree = {bestFeatLabel:{}}建立一个树,为了后面的赋值。
del(labels[bestFeat])删除类标签
featValues = [example[bestFeat] for example in dataSet]
uniqueVals = set(featValues)
for value in uniqueVals:
subLabels = labels[:] #copy all of labels, so trees don't mess up existing labels
myTree[bestFeatLabel][value] = createTree(splitDataSet(dataSet, bestFeat, value),subLabels)递归,每次调用两个creatTree,分两个字典给赋值。
结果如下:
>>> myDat,labels = trees.createDataSet()
>>> myTree = trees.createTree(myDat,labels)
>>> myTrees
Traceback (most recent call last):
File "", line 1, in
myTrees
NameError: name 'myTrees' is not defined
>>> myTree
{'no surfacing': {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}}