机器学习实战python版第三章决策树代码理解
来源:互联网 发布:sql 修改字段默认值 编辑:程序博客网 时间:2024/05/22 13:28
今天开始学习第三章决策树。
前面对决策树的讲解我就不写了,书上写的都很清楚,就是根据特征的不同逐步的对数据进行分类,形状像一个倒立的树。决策树算法比kNN的算法复杂度要低,理解起来也有一定难度。
信息增益
每一组数据都有自己的熵,数据要整齐,熵越低。也就是说属于同一类的数据熵低,越混合的数据熵越高。计算数据集的熵代码如下:
<span style="font-size:24px;">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</span>
划分数据集
就是根据一个特征把数据进行划分。代码如下:
<span style="font-size:24px;">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</span>
append,和extend这两个函数很有意思。
结果如下:
<span style="font-size:24px;">>>> 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']]</span>
但是实际操作中我们不能总能人工输入分类依据的特征。我们需要机器根据数据的特征自己判断最佳的分类特征。代码如下:
<span style="font-size:24px;">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</span>
结果如下:
<span style="font-size:24px;">>>> import trees>>> myDat,labels = trees.createDataSet()>>> trees.chooseBestFeatureToSplit(myDat)0</span>
建立决策树
书中的内容还是比较好理解的,树的建立理论也写得很详细,主要是代码比较难懂,因为python的代码很简洁,所以看起来也就更难一些。
创建树的函数代码:
<span style="font-size:24px;">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 </span>
首先这是一个递归函数,就是函数自己不停的调用自己,当遇到结束情况时在一步步返回。
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,分两个字典给赋值。
结果如下:
<span style="font-size:24px;">>>> myDat,labels = trees.createDataSet()>>> myTree = trees.createTree(myDat,labels)>>> myTreesTraceback (most recent call last): File "<pyshell#10>", line 1, in <module> myTreesNameError: name 'myTrees' is not defined>>> myTree{'no surfacing': {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}}</span>
下面的内容明天再写,希望大家多多指导!
- 机器学习实战python版第三章决策树代码理解
- 机器学习实战-第三章决策树-代码理解-读书笔记
- 机器学习实战-决策树ID3-python代码
- 机器学习实战+第三章_决策树
- 机器学习实战-第三章(决策树)
- 【读书笔记】机器学习实战-第三章 决策树
- 机器学习实战_初识决策树算法_理解其python代码(一)
- 机器学习实战_初识决策树(ID3)算法_理解其python代码(二)
- 机器学习实战 第三章 决策树 学习笔记
- 机器学习实战- 第三章 决策树-学习笔记
- 《机器学习实战》学习笔记-第三章-决策树
- 《机器学习实战》读书笔记 第三章 决策树(part 1)
- 《机器学习实战》读书笔记 第三章 决策树(part 3)
- 机器学习实战第三章——决策树程序
- 机器学习实战第三章——决策树(源码解析)
- [完]机器学习实战 第三章 决策树(Decision Tree)
- 【2】机器学习实战 第三章 决策树的构造
- 《机器学习实战》第三章 3.1 决策树的构造
- Makefile学习笔记
- 页面位置 top、postop、scrolltop、offsetTop、scrollHeight、offsetHeight、clientHeight
- 白话经典算法系列之五 归并排序的实现
- AES加密算法
- 【coder-pig教程学习笔记3】Http协议
- 机器学习实战python版第三章决策树代码理解
- Eclipse修改.ini配置,提高性能
- maven零散知识点记录
- 杭电1018
- 白话经典算法系列之四 直接选择排序及交换二个数据的正确实现
- 一个项目掌握80%的企业级项目开发技术
- Erlang手册supervisor翻译
- Java的诞生
- JavaScript学习之路03_字符串和数组