python3实现决策树(机器学习实战)


from math import log
def calcShannonEnt(dataSet):#计算给定数据集的香农熵
    numEntries = len(dataSet)
    labelCounts = {}
    for featVec in dataSet:
        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
        print(prob)
        shannonEnt -= prob * log(prob, 2)
    return shannonEnt



mydata = [[1, 1,'yes'], [1, 1,'yes'], [1, 0,'no'], [0, 1, 'no'], [0,1, 'no']]
print(calcShannonEnt(mydata))

def splitDataSet(dataSet, axis, value):#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
  #该函数是将数据集中第axis个特征的值为value的数据提取出来。
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
mydata = [[1, 1,'yes'], [1, 1,'yes'], [1, 0,'no'], [0, 1, 'no'], [0,1, 'no']]
print(chooseBestFeatureToSplit(mydata));

def majorityCnt(classList):#如果剩下的数据中无特征,则直接按最大百分比形成叶节点
    classCount = {}
    for vote in classList:
        if vote not in classCount.keys():
            classCount[vote] = 0
        classCount += 1;
    sortedClassCount = sorted(classCount.iteritems(), key = operator.itemgette(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) == 1:
        return majorityCnt(classList)
    bestFeat = chooseBestFeatureToSplit(dataSet)
    bestFeatLabel = labels[bestFeat]
    myTree = {bestFeatLabel:{}}
    del(labels[bestFeat])
    featvalue = [example[bestFeat] for example in dataSet]
    uniqueVals = set(featvalue)
    for value in uniqueVals:
        subLabels = labels[:]
        myTree[bestFeatLabel][value] = createTree(splitDataSet(dataSet, bestFeat, value), subLabels)
    return myTree

labels = ['no surface', 'flippers']
print(createTree(mydata, labels))

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