从 scikit-learn 决策树中提取决策规则
问题陈述:
可以将经过训练的决策树模型底层的决策规则提取为文本列表?
解决方案:
使用 tree_to_code 函数,可以生成一个有效的 Python 函数表示 scikit-learn 决策树的决策规则:
<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)) recurse(tree_.children_right[node], depth + 1) else: print("{}return {}".format(indent, tree_.value[node])) recurse(0, 1)</code>
示例:
对于尝试返回其输入(0 之间的数字)的决策树和 10),tree_to_code 函数将打印以下 Python 函数:
<code class="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.]]</code>
注意事项:
避免以下常见问题:
以上是如何从 scikit-learn 决策树中提取决策规则?的详细内容。更多信息请关注PHP中文网其他相关文章!