《机器学习实战》 第三章【决策树】

决策树(Decision Tree)是在已知各种情况发生概率的基础上,通过构成决策树来求取净现值的期望值大于等于零的概率,评价项目风险,判断其可行性的决策分析方法,是直观运用概率分析的一种图解法。
——百度百科
按照我个人的理解来解释就是,决策树是一种能够理解数据集中内含的知识信息并进行递归划分,直到划分为不可再分的标签为止,它是一种用于分类的递归算法。

目录

  • 算法描述
    • 算法简述
      • 信息增益
      • 熵:一种描述混乱度的量
    • 优缺点
    • 一般流程
  • 一个栗子
  • 预测隐形眼镜类型

算法描述

算法简述

def createBranch():
检测数据集中的每一个子项是否属于同一分类:
if yes:
	return 类标签
else:
	寻找划分数据集的最好特征 #利用熵进行选择
	划分数据集
	创建分支节点
		for每一个划分的子集
			调用createBranch()	#这里就是自身递归调用的位置
	return 分支节点

所以,算法的重点就在于如何寻找划分数据集的最好特征如何划分数据集

信息增益

  • 划分数据集的大原则:将无序数据变得更加有序
  • 一种方法是使用“信息论”度量信息
  • 在划分数据集之前之后信息发生的变化称为信息增益
  • 使用香农公式计算将信息增益(混乱程度)

熵:一种描述混乱度的量

熵定义为信息的期望值,如果待分类的食物可能划分在多个分类中,则符号xi的信息定义为:
在这里插入图片描述
p(xi)是描述该分了的概率,而H描述了所以类别所有可能值的信息期望值:
在这里插入图片描述

优缺点

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

一般流程

  • 收集数据:任何方法
  • 准备数据:树构造算法只适用于标称型数据,因此数值型数据必须离散化
  • 分析数据:任何方法,构造树完成后,我们应该检查图形是否符合预期
  • 训练算法:构造树的数据结构
  • 测试算法:使用经验树计算错误率
  • 使用算法:可以适用于任何监督学习算法

一个栗子

#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 #如果没有,字典自动补齐1个
        labelCounts[currentLabel] += 1 #加1个
    shannonEnt = 0.0 #香农值
    #print(labelCounts)
    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 surffering','flippers']
    return dataSet,labels

#按照给定特征划分数据集
#parameter1:待划分的数据集
#paramenter2:第axis列
#paramenter3:返回值为value的部分
#顺便去掉第axis列
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):
    numFeatures = len(dataSet[0]) - 1      #得到特征数,去掉最后一列的标签
    baseEntropy = calcShannonEnt(dataSet)   #初始化
    bestInfoGain = 0.0; bestFeature = -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                      #返回最优特征

def majorityCnt(classList):
    classCount={}
    for vote in classList:
        if vote not in classCount.keys(): classCount[vote]=0
        classCount[vote]+=1
        sortedclassCount=sorted(classCount.items(),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: {}}
    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


myDat,labels=createDataSet()
myTree=createTree(myDat,labels)
print(myTree)


结果:得到一棵树
《机器学习实战》 第三章【决策树】_第1张图片

预测隐形眼镜类型

#coding:utf-8
from math import log
import operator
import treePlotter
def createDataSet():
    dataSet = [[1, 1, 'yes'],
               [1, 1, 'yes'],
               [1, 0, 'no'],
               [0, 1, 'no'],
               [0, 1, 'no']]
    labels = ['no surfacing','flippers']
    #change to discrete values
    return dataSet, labels

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]     #chop out axis used for splitting
            reducedFeatVec.extend(featVec[axis+1:])
            retDataSet.append(reducedFeatVec)
    return retDataSet
    
def chooseBestFeatureToSplit(dataSet):
    numFeatures = len(dataSet[0]) - 1      #the last column is used for the labels
    baseEntropy = calcShannonEnt(dataSet)
    bestInfoGain = 0.0; bestFeature = -1
    for i in range(numFeatures):        #iterate over all the features
        featList = [example[i] for example in dataSet]#create a list of all the examples of this feature
        uniqueVals = set(featList)       #get a set of unique values
        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

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                            
    
def classify(inputTree,featLabels,testVec):
    firstStr = inputTree.keys()[0]
    secondDict = inputTree[firstStr]
    featIndex = featLabels.index(firstStr)
    key = testVec[featIndex]
    valueOfFeat = secondDict[key]
    if isinstance(valueOfFeat, dict): 
        classLabel = classify(valueOfFeat, featLabels, testVec)
    else: classLabel = valueOfFeat
    return classLabel

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)

fr=open('lenses.txt')
lenses=[inst.strip().split('\t') for inst in fr.readlines()]
lensesLabel=['age','prescript','astigmatic','tearRate']
lensesTree=createTree(lenses,lensesLabel)
treePlotter.createPlot(lensesTree)

结果:
《机器学习实战》 第三章【决策树】_第2张图片

你可能感兴趣的:(机器学习)