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 机器学习实战-用递归方法创建树
最新推荐文章于 2025-09-22 23:11:09 发布
本文深入讲解了决策树算法的核心原理及实现过程。通过定义createTree函数来递归地创建决策树,选择最佳划分特征,并根据该特征的不同取值继续划分数据集。当所有样本属于同一类别或无法再进行特征划分时,递归终止。
部署运行你感兴趣的模型镜像
您可能感兴趣的与本文相关的镜像
LobeChat
AI应用
LobeChat 是一个开源、高性能的聊天机器人框架。支持语音合成、多模态和可扩展插件系统。支持一键式免费部署私人ChatGPT/LLM 网络应用程序。
419

被折叠的 条评论
为什么被折叠?



