ホームページ  >  記事  >  バックエンド開発  >  Python で Scikit-Learn デシジョン ツリーからデシジョン ルールを抽出する方法

Python で Scikit-Learn デシジョン ツリーからデシジョン ルールを抽出する方法

Susan Sarandon
Susan Sarandonオリジナル
2024-10-26 12:18:03838ブラウズ

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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。