如何构建决策树?
我们知道树的构建过程是递归,递归最终要的就是找到边界条件,决策树的递归结束条件是:
1、程序遍历玩所有划分的数据集的属性;
2、每个分支下的所有势力都具有相同的分类;
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 |
代码解析:构建的input有两个,一个是数据集中所有的特征的标签,另一个是数据集;标签列表包含了数据集中所有的特征的标签,算法本身不需要此输入,但为了给胡数据的明确定义,将他作为一个参考;首先代码先构建一个classList列表变量,包含了数据集中的所有标签。停止条件一:所有的标签完全相同,则直接返回该类标签;停止条件二:使用完了所有特征,由于呢,第二个条件无法简单的返回唯一的类标签(也就是说在这个条件下有可能出现多个类标签)---这里使用majorrityCnt挑选出现次数最多的类别作为返回值。
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] |