从 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中文网其他相关文章!