机器学习-决策树

深藏阁楼爱情的钟 2022-05-31 07:15 565阅读 0赞

此文章是《Machine Learning in Action》中决策树章节的学习笔记,
决策树可以使用不熟悉的数据集合,并从中提取出一系列规则,在这些机器根据数据集创建规则时,就是机器学习的过程。

  1. 优点:计算复杂度不高,输出结果易于理解,对中间值的缺失不敏感,可以处理不相关特征数据
  2. 缺点:可能会产生过度匹配问题
  3. 适用数据类型:数值型和标称型

1 香农熵
香农熵百度百科,信息量的度量就等于不确定性的多少。变量的不确定性越大,熵也就越大,把它搞清楚所需要的信息量也就越大。
1

  1. # -*- coding: utf-8 -*-
  2. ''' Created on 2018年02月21日 @author: dzm '''
  3. from math import log
  4. def createDataSet():
  5. ''' 数据集, 第一列 不浮出水面是否可以生存 第二列 是否有脚蹼 第三列 属于鱼类 :return: '''
  6. dataSet = [[1, 1, 'yes'],
  7. [1, 1, 'yes'],
  8. [1, 0, 'no'],
  9. [0, 1, 'no'],
  10. [0, 1, 'no']]
  11. labels = ['no surfacing','flippers']
  12. #change to discrete values
  13. return dataSet, labels
  14. def calcShannonEnt(dataSet):
  15. ''' 计算香农熵 :param dataSet: :return: '''
  16. numEntries = len(dataSet)
  17. labelCounts = {}
  18. for featVec in dataSet: #the the number of unique elements and their occurance
  19. currentLabel = featVec[-1]
  20. if currentLabel not in labelCounts.keys(): labelCounts[currentLabel] = 0
  21. labelCounts[currentLabel] += 1
  22. shannonEnt = 0.0
  23. for key in labelCounts:
  24. # 计算分类的概率
  25. prob = float(labelCounts[key])/numEntries
  26. # 计算香农熵
  27. shannonEnt -= prob * log(prob,2) #log base 2
  28. return shannonEnt
  29. if __name__ == '__main__':
  30. myDat, labels = createDataSet()
  31. print calcShannonEnt(myDat)

2 划分数据集

  1. def splitDataSet(dataSet, axis, value):
  2. ''' 划分数据集 :param dataSet: 待划分的数据集 :param axis: 划分数据集的特征 :param value: 需要返回的特征值 :return: '''
  3. retDataSet = []
  4. for featVec in dataSet:
  5. if featVec[axis] == value:
  6. reducedFeatVec = featVec[:axis] #chop out axis used for splitting
  7. reducedFeatVec.extend(featVec[axis+1:])
  8. retDataSet.append(reducedFeatVec)
  9. return retDataSet
  10. def chooseBestFeatureToSplit(dataSet):
  11. ''' 选择最好的数据集划分方式 :param dataSet: :return: '''
  12. numFeatures = len(dataSet[0]) - 1 #the last column is used for the labels
  13. # 计算整个数据集的原始香农熵
  14. baseEntropy = calcShannonEnt(dataSet)
  15. bestInfoGain = 0.0; bestFeature = -1
  16. for i in range(numFeatures): #iterate over all the features
  17. featList = [example[i] for example in dataSet]#create a list of all the examples of this feature
  18. uniqueVals = set(featList) #get a set of unique values
  19. newEntropy = 0.0
  20. for value in uniqueVals:
  21. subDataSet = splitDataSet(dataSet, i, value)
  22. prob = len(subDataSet)/float(len(dataSet))
  23. newEntropy += prob * calcShannonEnt(subDataSet)
  24. infoGain = baseEntropy - newEntropy #calculate the info gain; ie reduction in entropy
  25. if (infoGain > bestInfoGain): #compare this to the best gain so far
  26. # 讲每个特征对应的熵进行比较,选择熵值最小的,作为特征划分的索引值
  27. bestInfoGain = infoGain #if better than current best, set to best
  28. bestFeature = i
  29. return bestFeature #returns an integer

3 决策树

  1. def majorityCnt(classList):
  2. ''' :param classList: :return: '''
  3. classCount={}
  4. for vote in classList:
  5. if vote not in classCount.keys(): classCount[vote] = 0
  6. classCount[vote] += 1
  7. sortedClassCount = sorted(classCount.iteritems(), key=operator.itemgetter(1), reverse=True)
  8. return sortedClassCount[0][0]
  9. def createTree(dataSet,labels):
  10. ''' 构建决策树 :param dataSet: 数据集 :param labels: 标签列表,包含了数据集中所有特征的标签 :return: '''
  11. classList = [example[-1] for example in dataSet]
  12. if classList.count(classList[0]) == len(classList):
  13. return classList[0]#stop splitting when all of the classes are equal
  14. if len(dataSet[0]) == 1: #stop splitting when there are no more features in dataSet
  15. return majorityCnt(classList)
  16. bestFeat = chooseBestFeatureToSplit(dataSet)
  17. bestFeatLabel = labels[bestFeat]
  18. # 存储数据的信息
  19. myTree = {bestFeatLabel:{}}
  20. del(labels[bestFeat])
  21. featValues = [example[bestFeat] for example in dataSet]
  22. uniqueVals = set(featValues)
  23. for value in uniqueVals:
  24. subLabels = labels[:] #copy all of labels, so trees don't mess up existing labels
  25. myTree[bestFeatLabel][value] = createTree(splitDataSet(dataSet, bestFeat, value),subLabels)
  26. return myTree

发表评论

表情:
评论列表 (有 0 条评论,565人围观)

还没有评论,来说两句吧...

相关阅读

    相关 机器学习-04决策

    4、决策树 4.1 决策树基本概念 顾名思义,决策树是基于树结构来进行决策的,在网上看到一个例子十分有趣,放在这里正好合适。现想象一位捉急的母亲想要给自己的女娃介绍

    相关 机器学习-决策

    决策树是常见的机器学习算法。类似于人类在面临决策问题时的自然处理机制,是基于树结构来进行决策的。例如,我们要对“这是好瓜吗?”的问题进行决策,通常会进行一系列的子决策:我们会先

    相关 机器学习基础--决策

    决策树是很基础很经典的一个分类方法,基本上很多工业中很使用且常用的算法基础都是决策树,比如boost,GBDT,CART(分类回归树),我们后需会慢慢分析,决策时定义如下:

    相关 机器学习决策 总结

    具体的细节概念就不提了,这篇blog主要是用来总结一下决策树的要点和注意事项,以及应用一些决策树代码的。 一、决策树的优点: • 易于理解和解释。数可以可视化。也就是说

    相关 机器学习决策

    决策树 【关键词】树,熵,信息增益 决策树的优缺点 优点:计算复杂度不高,输出结果易于理解,对中间值的缺失不敏感,可以处理不相关特征数据。既能用于分类,也能用