首页  >  文章  >  后端开发  >  如何从 scikit-learn 决策树中提取决策规则?

如何从 scikit-learn 决策树中提取决策规则?

Mary-Kate Olsen
Mary-Kate Olsen原创
2024-10-27 09:14:03870浏览

How to Extract Decision Rules from scikit-learn Decision Trees?

从 scikit-learn 决策树中提取决策规则

问题陈述:

可以将经过训练的决策树模型底层的决策规则提取为文本列表?

解决方案:

使用 tree_to_code 函数,可以生成一个有效的 Python 函数表示 scikit-learn 决策树的决策规则:

<code class="python">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)</code>

示例:

对于尝试返回其输入(0 之间的数字)的决策树和 10),tree_to_code 函数将打印以下 Python 函数:

<code class="python">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.]]</code>

注意事项:

避免以下常见问题:

  • 不要依赖tree_.threshold == -2来识别叶子节点;检查tree.feature或tree.children_*。
  • 正确指定特征名称,避免可能对应于未定义特征的整数。
  • 在递归函数中单个if语句就足够了。

以上是如何从 scikit-learn 决策树中提取决策规则?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn