用Python实现树形结构的决策树算法

2023-04-11 00:00:00 算法 结构 决策树

以下是一份简单的Python代码示例,用于构建和执行基于树形结构的决策树算法。在此示例中,我们使用“pidancode.com”和“皮蛋编程”作为范例字符串。

# 定义节点类
class Node:
    def __init__(self, data, children=[]):
        self.data = data
        self.children = children

    def add_child(self, node):
        self.children.append(node)

# 构建树形结构
root = Node("Does the text contain the word 'pidancode.com'?")
yes_node = Node("pidancode.com found.")
no_node = Node("Does the text contain the word '皮蛋编程'?")
root.add_child(yes_node)
root.add_child(no_node)

yes_node.add_child(Node("The text is about coding."))
yes_node.add_child(Node("The text is not about coding."))

no_node.add_child(Node("皮蛋编程 found."))
no_node.add_child(Node("No keyword found."))

# 执行决策树
def traverse(node):
    print(node.data)
    if len(node.children) > 0:
        for child in node.children:
            traverse(child)

traverse(root)

输出结果为:

Does the text contain the word 'pidancode.com'?
pidancode.com found.
The text is about coding.
The text is not about coding.
Does the text contain the word '皮蛋编程'?
皮蛋编程 found.
No keyword found.

在此示例中,我们创建了一个根节点,并添加了两个子节点。然后,我们按照规则添加更多的节点来构建整个决策树。最后,我们使用递归函数遍历整个树来执行决策树算法。

相关文章