《机器学习实战》学习笔记(3、决策树)

k-近邻算法,可以完成很多分类任务。但最大的缺点就是,无法给出数据的内在含义

决策树的主要优势在于,数据形式非常容易理解。

决策树的一个重要任务,使用不熟悉的数据集合,并从中提取出一系列规则,在这些机器根据,数据集创建规则时,就是机器学习的过程。

优点:计算复杂度低,输出结果易于理解,对中间值的缺失不敏感,可处理不相关特征数据。

缺点:可能会产生过度匹配问题。

适用于,数值型和标称型。

 

在构建决策树时,需要考虑的第一个问题是,当前数据集上,哪个特征在划分数据分类时,起决定性作用。

因此需要评估每个特征。

完成测试后,数据集会被划分为几个数据子集,这些子集分布在决策树,第一个决策点的所有分支上。

若某个分支上的数据属于同一类型,则无需进一步分割。

 

决策树的一般流程:

准备数据(树构造算法的数值型数据,必须要离散化)、测试算法(使用经验树计算错误率)

采用量化的方法,判断如何划分数据:信息增益

信息增益:在划分数据集之前之后,信息发生的变化。

获得信息增益最高的特征,就是最好的选择。

集合信息的,度量方式,称为香农熵。计算方式:信息的期望值

计算给定数据集的香农熵:

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 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 splitDataSet(dataSet, axis, value):
    # 待划分的数据、划分数据集的特征、需要返回的特征值
    retDataSet = []
    for featVec in dataSet:
        if featVec[axis] == value:
            reducedFeatVec = featVec[:axis]
            # extend合并两个列表
            reducedFeatVec.extend(featVec[axis + 1:])
            # reducedFeatVec已经剔除掉了,划分数据集的特征
            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):  # 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
        if (infoGain > bestInfoGain):
            bestInfoGain = infoGain
            bestFeature = i
    return bestFeature

结果返回0,表示按第一个特征属性划分数据最好。也即,第一个特征是1的放在一个组,第一个特征是0的放在另一个组。

得到的结果为,第一个特征为1的海洋生物分组将有,两个属于鱼类,一个属于非鱼类;另一个分组则全部属于非鱼类。

 

递归构建决策树:

返回类标签,出现次数最多的,分类名称:

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]
    # dataSet里的预测类别全都相同,则停止划分
    if classList.count(classList[0]) == len(classList):
        return classList[0]  # 返回该类别
    if len(dataSet[0]) == 1:  # dataSet只有标签列了
        return majorityCnt(classList)  # 返回出现次数最多的预测值
    # 当前数据集,选取的最好最好特征,bestFeat是个列序号
    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[:]
        # splitDataSet返回,剔除掉指定列bestFeat与value相等的数据集
        myTree[bestFeatLabel][value] = createTree(splitDataSet(dataSet, bestFeat, value), subLabels)
        # 在字典里,嵌入另外的以键值为01的字典
    return myTree

工作原理:得到原始数据集,然后基于最好的属性值划分数据集,由于特征值可能多于两个,因此存在大于两个分支的数据集划分。第一次划分后,数据将被向下传递到树分支的下一个节点,在这个分支上,再次划分数据。

递归结束:1、遍历完所有划分数据集的属性。2、每个分支下的所有实例,具有相同的分类。

 

在Python中使用Matplotlib注解绘制树形图:

使用Matplotlib提供的一个注解工具annotations。可以在数据图像上,添加文本注释,通常用于解释数据的内容。

使用文本注解绘制树节点:

# 定义文本框和箭头格式
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(U'决策节点', (0.5, 0.1), (0.1, 0.5), decisionNode)
    plotNode(U'叶节点', (0.8, 0.1), (0.3, 0.8), leafNode)
    plt.show()

构造注解树:

要先确定x、y坐标,则先获取叶节点的数量和树有多少层。

def getNumLeafs(myTree):
    numLeafs = 0
    firstStr = list(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 = list(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 classify(inputTree, featLabels, testVec):
    firstStr = inputTree.keys()[0]  # 查找当前列表中第一个匹配firstStr变量的元素
    secondDict = inputTree[firstStr]
    featIndex = featLabels.index(firstStr)  # 在featLabels中,获取判断节点的索引
    key = testVec[featIndex]  # key取值为0或1
    valueOfFeat = secondDict[key]  # valueOfFeat取出为字典或类标签
    if isinstance(valueOfFeat, dict):
        classLabel = classify(valueOfFeat, featLabels, testVec)
    else:
        classLabel = valueOfFeat
    return classLabel

# 将决策树序列化
def grabTree(filename):
    import pickle
    fr = open(filename)
    return pickle.load(fr)


myTree = grabTree('classifierStorage.txt')
myDat, labels = createDataSet()
print(classify(myTree, labels, [1, 0]))
print(classify(myTree, labels, [1, 1]))

ID3算法:

若匹配选项太多,则会发生过度匹配现象。可裁剪决策树,若叶子节点只能增加少许信息,则可删除该节点,将它并入到其它叶子节点中。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值