從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中文網其他相關文章!