首页 > 解决方案 > DecisionTreeClassifier - 手动修剪树

问题描述

我正在制作一个交互式建模工具。这个想法是用决策树产生变量。但是,这个变量需要具有经济意义(我希望能够删除理论上没有意义的拆分)。因此,我用 plotly 绘制了一棵树,以便能够听到用户点击的位置。我在下面附上一张图片。

我的问题是我是否可以手动删除一个节点。我可以捕获点击,即您要删除哪个节点;但是我在 DecisionTreeClassifier 中看不到手动删除特定节点的选项。

示例树 全尺寸图像

非常感谢。

马林

标签: pythonplotlydecision-treeinteractive

解决方案


根据马克西米利安的建议,我访问了链接并稍微调整了代码以创建:

from sklearn.tree._tree import TREE_LEAF

def prune_index(inner_tree, index):
     # turn node into a leaf by "unlinking" its children
     inner_tree.children_left[index] = TREE_LEAF
     inner_tree.children_right[index] = TREE_LEAF
 # if there are shildren, visit them as well
     if inner_tree.children_left[index] != TREE_LEAF:
         prune_index(inner_tree, inner_tree.children_left[index])
         prune_index(inner_tree, inner_tree.children_right[index])

奇迹般有效!谢谢!!


推荐阅读