1:什么是决策树
顾名思义:决策树就是根据已有的条件进行决策从而产生的一棵树。
比如,这就是一颗决策树,根据不同的取值决定不同的走向
2、那么如何根据现有的属性来决定谁是第一个节点,谁是第二个节点呢,这里就要用到ID3算法了
Id3 算法大家可以搜一下,就是利用信息熵来计算的,根据信息增益每次找到最合适的来当树根,这样,就会更符合实际情况
3、有了建树的方法,接下来就是进行建树,建树是递归建立的,代码在底下,大家可以自己理解一下
4:最后利用输入训练数据进行训练,然后对测试数据进行树上的查找,从而进行预测
import numpy
from math import log
import operator
import treePlotter
# 计算熵的函数
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
# 测试
# dataSet , labels =createDataSet()
# ans = calcShannonEnt(dataSet)
# 熵越高,混合的数据就越多
# print(ans)
# 划分数据集,没有计算熵,直接分类
def splitDataSet(dataSet, axis, value):
# 参数: 待划分的数据集,划分数据集的特征的列,按照该列进行分类的值,如果该列中有符合这个value的值,那么就会被分为一类
# 注意:python 语言在函数中传递的是列表的引用,在函数内部对列表对象的修改,
# 将会直接影响列表对象,所以,这里重新声明了一个列表
retDataSet = []
# dataSet中的数据也是列表
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.items(), key=operator.itemgetter(1), reverse=True)
return sortedClassCount[0][0]
# 递归构造决策树,ID3 算法
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
# 划分数据集测试
dataSet , labels =createDataSet()
# ans = splitDataSet(dataSet,0,0) # 对dataset进行分类,按照地0列,值为0的进行归类
# print(ans)
# ans = chooseBestFeatureToSplit(dataSet)
# print("对结果影响最大的一列是:"+str(ans))
# 构造决策树
myTree = createTree(dataSet,labels)
# print(myTree)
# 使用matplotlib 绘制树
##################### 省略
# 测试算法:使用决策树进行分类
# 使用决策树的分类函数
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
# 使用pickle 模块存储决策树
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)
本来想利用决策树优化手写数字的识别,但是暂时没写出来。。。还是不太回写。。。后期再发吧。。
参考文献-machine learning -peter harrington