我可以从决策树中的一棵经过训练的树中提取底层决策规则(或"决策路径")作为文本列表吗?

比如:

if A>0.4 then if B<0.2 then if C>0.8 then class='X'

推荐答案

我相信这个答案比这里的其他答案更正确:

from sklearn.tree import _tree

def tree_to_code(tree, feature_names):
    tree_ = tree.tree_
    feature_name = [
        feature_names[i] if i != _tree.TREE_UNDEFINED else "undefined!"
        for i in tree_.feature
    ]
    print "def tree({}):".format(", ".join(feature_names))

    def recurse(node, depth):
        indent = "  " * depth
        if tree_.feature[node] != _tree.TREE_UNDEFINED:
            name = feature_name[node]
            threshold = tree_.threshold[node]
            print "{}if {} <= {}:".format(indent, name, threshold)
            recurse(tree_.children_left[node], depth + 1)
            print "{}else:  # if {} > {}".format(indent, name, threshold)
            recurse(tree_.children_right[node], depth + 1)
        else:
            print "{}return {}".format(indent, tree_.value[node])

    recurse(0, 1)

这将打印出有效的Python函数.下面是试图返回其输入(0到10之间的数字)的树的示例输出.

def tree(f0):
  if f0 <= 6.0:
    if f0 <= 1.5:
      return [[ 0.]]
    else:  # if f0 > 1.5
      if f0 <= 4.5:
        if f0 <= 3.5:
          return [[ 3.]]
        else:  # if f0 > 3.5
          return [[ 4.]]
      else:  # if f0 > 4.5
        return [[ 5.]]
  else:  # if f0 > 6.0
    if f0 <= 8.5:
      if f0 <= 7.5:
        return [[ 7.]]
      else:  # if f0 > 7.5
        return [[ 8.]]
    else:  # if f0 > 8.5
      return [[ 9.]]

以下是我在其他答案中看到的一些绊脚石:

  1. 使用tree_.threshold == -2来确定 node 是否为叶不是一个好主意.如果它是一个阈值为-2的真实决策 node 呢?相反,你应该看tree.featuretree.children_*.
  2. features = [feature_names[i] for i in tree_.feature]行在我的sklearn版本中崩溃,因为tree.tree_.feature的一些值是-2(特别是对于叶 node ).
  3. 递归函数中不需要有多条if语句,只需一条即可.

Python相关问答推荐

如果我已经使用了time,如何要求Python在12秒后执行另一个操作.sleep

具有2D功能的Python十六进制图

"Discord机器人中缺少所需的位置参数ctx

过滤绕轴旋转的螺旋桨

使文本输入中的文本与标签中的文本相同

如何使用Jinja语法在HTML中重定向期间传递变量?

Python 约束无法解决n皇后之谜

如何记录脚本输出

在Python中管理打开对话框

ODE集成中如何终止solve_ivp的无限运行

从一个系列创建一个Dataframe,特别是如何重命名其中的列(例如:使用NAs/NaN)

关于Python异步编程的问题和使用await/await def关键字

如何使用Pandas DataFrame按日期和项目汇总计数作为列标题

名为__main__. py的Python模块在导入时不运行'

在www.example.com中使用`package_data`包含不包含__init__. py的非Python文件

使用Python查找、替换和调整PDF中的图像'

如何检测鼠标/键盘的空闲时间,而不是其他输入设备?

从一个df列提取单词,分配给另一个列

在极点中读取、扫描和接收有什么不同?

Polars时间戳同步延迟计算