【问题标题】:Recursion in trees树中的递归
【发布时间】:2015-03-19 11:50:33
【问题描述】:

我正在用 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)

【问题讨论】:

    标签: python recursion tree decision-tree


    【解决方案1】:

    递归调用应该用于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
    

    【讨论】:

    • 我可以看到它是如何工作的,但是节点需要属性“vectors”来决定在哪个特征上分割树,如果我在那个时候递归它就没有了。
    • 所以先设置属性,然后再进行递归调用(切换行的顺序)。
    【解决方案2】:

    您的函数只能返回一次,这就是它只构建正确节点的原因;它也不应该返回它的子节点。您是否尝试将最后几行替换为:

    for node in nodeList:
        node = buildTree(node, maxDepth, currentDepth + 1, minGain, maxGain, allFeatures)
    return currentNode
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-05
      • 2017-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-12
      相关资源
      最近更新 更多