首頁 >後端開發 >Python教學 >如何從 scikit-learn 決策樹中提取決策規則?

如何從 scikit-learn 決策樹中提取決策規則?

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-10-27 09:14:03984瀏覽

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