如何用 Python 從 Scikit-Learn 決策樹中擷取決策規則?

Susan Sarandon
發布: 2024-10-26 12:18:03
原創
850 人瀏覽過

How to Extract Decision Rules from Scikit-Learn Decision Trees in Python?

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

從經過訓練的決策樹中提取底層決策規則可以為其決策提供有價值的見解- 製作過程。以下是如何使用 Python 以文字清單格式執行此操作。

Python 函數:

<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) + depth)
            recurse(tree_.children_right[node], depth + 1)
        else:
            print("{}return {}".format(indent, tree_.value[node]))

    recurse(0, 1)</code>
登入後複製

範例用法:

<code class="python">tree_model = DecisionTreeClassifier().fit(X, y)
tree_to_code(tree_model, feature_names)</code>
登入後複製

這個函數在樹結構上,該函數在迭代遇到每個分支時列印出決策規則。它處理葉子節點和非葉子節點,並產生一個有效的 Python 函數來封裝樹的決策過程。

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

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!