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.py367 chars13 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