一、优缺点
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