get decison rules for decision tree sklearn in python

You can use the export_text function from the sklearn.tree module to get the decision rules for a decision tree in scikit-learn. Here is an example:

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

# Load the iris dataset
iris = load_iris()

# Train a decision tree classifier
clf = DecisionTreeClassifier()
clf.fit(iris.data, iris.target)

# Get the decision rules
rules = export_text(clf, feature_names=iris.feature_names)
print(rules)
341 chars
14 lines

Output:

main.py
|--- petal length (cm) <= 2.45
|   |--- class: 0
|--- petal length (cm) >  2.45
|   |--- petal width (cm) <= 1.75
|   |   |--- petal length (cm) <= 4.95
|   |   |   |--- class: 1
|   |   |--- petal length (cm) >  4.95
|   |   |   |--- petal width (cm) <= 1.55
|   |   |   |   |--- class: 2
|   |   |   |--- petal width (cm) >  1.55
|   |   |   |   |--- class: 1
|   |--- petal width (cm) >  1.75
|   |   |--- petal length (cm) <= 4.85
|   |   |   |--- sepal width (cm) <= 3.10
|   |   |   |   |--- class: 2
|   |   |   |--- sepal width (cm) >  3.10
|   |   |   |   |--- class: 1
|   |   |--- petal length (cm) >  4.85
|   |   |   |--- class: 2
644 chars
20 lines

The decision rules show the conditions for each split in the tree, and the corresponding class that resulting samples belong to.

gistlibby LogSnag