how to extract the decision rules from scikit-learn decision-tree? in python

Once you have fit a decision tree model using scikit-learn, you can extract the decision rules that define the tree by using the tree_.feature, tree_.threshold, and tree_.children attributes of the trained DecisionTreeClassifier or DecisionTreeRegressor. Here is a sample code snippet that shows how to extract the rules from a decision tree model trained on the iris dataset using scikit-learn:

main.py
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier, export_text

iris = load_iris()
X, y = iris.data, iris.target
clf = DecisionTreeClassifier(random_state=0, max_depth=2)
clf.fit(X, y)

# Extracting decision rules
tree_rules = export_text(clf, feature_names=iris.feature_names).split('\n')
for rule in tree_rules:
    print(rule)
367 chars
13 lines

The main function used here is export_text which generates a human-readable textual representation of the decision tree. The feature_names parameter is used in the function call to specify the names of the features in the dataset.

The resulting tree_rules variable contains the extracted rules for the decision tree, in the form of a list of strings, one for each rule. Each rule is formatted as a human-readable text string, that specifies the feature, threshold, and direction (less/greater than the threshold) of the decision at each node of the tree.

gistlibby LogSnag