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