机器学习实战第三章(决策树)

本文详细介绍了决策树算法的原理及实现过程,包括决策树构建的基本步骤、信息增益的计算方法,以及如何通过划分数据集选取最佳特征进行决策。

一、优缺点

K邻近算法最大的缺点是无法给出数据的内在含义,决策树的优势就在于数据形式非常容易理解。

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

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

适用数据类型为:数值型和标称型

二、构造决策树步骤

1.当前数据集中那个特征在划分数据分类时候起决定性作用。

 1.1信息增益
      在划分数据集之前之后数据所发生的变化成为信息增益,知道如何计算信息增益,计算每个特征值的增益然后选取最高的就是最好的选择。

      集合信息的度量方式成为香农熵

输入图片说明

三、步骤

1.收集收据
2.准备数据
3.分析数据
4.训练算法
5.测试算法
6.使用算法
'''
香农熵 对于某一个键值的
'''
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
'''
dataSet:待划分的数据集
axis:划分数据集的特征
value:特征返回值
 featVec[:axis] 前面冒号之前的数据不包含当前
featVec[axis+1:]后面冒号之后的数据包含当前的
'''
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:])  #extend方法是把当前元素提取出来后放在后面 
            retDataSet.append(reducedFeatVec)         #append方法是直接把当前的元素放在后面
    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

转载于:https://my.oschina.net/findurl/blog/1580065

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值