首頁  >  文章  >  後端開發  >  如何從 Scikit-Learn 決策樹中提取決策規則?

如何從 Scikit-Learn 決策樹中提取決策規則?

DDD
DDD原創
2024-10-28 02:26:02887瀏覽

How to Extract Decision Rules from a Scikit-Learn Decision Tree?

從Scikit-Learn 決策樹中提取決策規則

決策樹是一種廣泛使用的機器學習演算法,透過建模決策提供見解流程作為規則的層次結構。然而,明確提取這些決策規則可能具有挑戰性。本文概述了從經過訓練的 Scikit-Learn 決策樹中提取文本決策規則的綜合方法。

決策規則擷取的Python 程式碼

以下Python 程式碼片段使用Scikit-Learn 決策樹的底層資料結構,用於遍歷並產生人類可讀的程式碼片段使用Scikit-Learn 決策樹的底層資料結構,用於遍歷並產生人類可讀的程式碼片段決策路徑:

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 函數

此程式碼遍歷遞歸樹,列印每個條件分割和閾值。結果是一個有效的 Python 函數,它有效地模擬了經過訓練的決策樹的決策過程。

範例輸出

例如,考慮一棵樹,它嘗試返回其輸入,一個 0 到 10 之間的數字。產生的 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.]]

優點和注意事項

此方法提供了清晰且樹的決策規則的可測試表示。但是,請注意,程式碼假設樹中的每個節點都是二元決策節點。如果您的決策樹包含非二元決策節點,您將需要相應地調整程式碼。

以上是如何從 Scikit-Learn 決策樹中提取決策規則?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn