gpt4 book ai didi

python - 树中的递归

转载 作者:行者123 更新时间:2023-12-01 04:52:56 25 4
gpt4 key购买 nike

我正在用 Python 构建一个简单的二元决策树。我正在使用递归来构建树,但是,作为一个没有牢固掌握这个概念的人,我遇到了一些麻烦。我想在树达到一定深度时停止递归,但我不确定在哪里增加该值,因此它一次会构建多个分支。现在,树只是向右分支,直到达到 5,然后停止。我应该在哪里/如何增加该值?现在我正在函数底部的 for 循环中执行此操作。

def buildTree(currentNode, maxDepth, currentDepth, minGain, currentGain, allFeatures):
print(currentNode.data)
if maxDepth <= currentDepth:
return None
else:
splitOn, hasFeat, noFeat, allFeatures, maxGain = split(currentNode, allFeatures)
print(len(hasFeat), len(noFeat))
currentNode.left = Tree()
currentNode.left.vectors = hasFeat
currentNode.left.data = splitOn
currentNode.left.entropy = getEntropy(getInstances(currentNode.left.vectors))
currentNode.right = Tree()
currentNode.right.vectors = noFeat
currentNode.right.data = "!" + splitOn
currentNode.right.entropy = getEntropy(getInstances(currentNode.right.vectors))
nodeList = [currentNode.right, currentNode.left]
for node in nodeList:
return buildTree(node, maxDepth, currentDepth + 1, minGain, maxGain, allFeatures)

最佳答案

应该在 currentNode.leftcurrentNode.right 上使用递归调用。

代码应该是这样的:

def buildTree(currentNode, maxDepth, currentDepth, minGain, currentGain, allFeatures):
print(currentNode.data)
if maxDepth <= currentDepth:
return None
else:
splitOn, hasFeat, noFeat, allFeatures, maxGain = split(currentNode, allFeatures)
print(len(hasFeat), len(noFeat))
currentNode.left = buildTree(Tree(), maxDepth, currentDepth + 1, minGain, maxGain, allFeatures)
currentNode.left.vectors = hasFeat
currentNode.left.data = splitOn
currentNode.left.entropy = getEntropy(getInstances(currentNode.left.vectors))
currentNode.right = buildTree(Tree(), maxDepth, currentDepth + 1, minGain, maxGain, allFeatures)
currentNode.right.vectors = noFeat
currentNode.right.data = "!" + splitOn
currentNode.right.entropy = getEntropy(getInstances(currentNode.right.vectors))
nodeList = [currentNode.right, currentNode.left]
return nodeList

关于python - 树中的递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28059103/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com