show decision tree sklearn in python

After training a decision tree classifier using Scikit-learn library, we can also visualize the tree structure by using the export_graphviz function from the sklearn.tree module. Here's an example:

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

# Load the Iris dataset
iris = load_iris()

# Train the decision tree classifier
dectree = DecisionTreeClassifier()
dectree.fit(iris.data, iris.target)

# Visualize the decision tree
export_graphviz(dectree, out_file='tree.dot', 
                feature_names=iris.feature_names,  
                class_names=iris.target_names,
                filled=True, rounded=True,  
                special_characters=True)

# Convert the dot file to png or display it using any graphviz viewer
# For example, using pydotplus and Graphviz:
import pydotplus
from IPython.display import Image

dot_data = export_graphviz(dectree, out_file=None, 
                           feature_names=iris.feature_names,  
                           class_names=iris.target_names,
                           filled=True, rounded=True,  
                           special_characters=True)
graph = pydotplus.graph_from_dot_data(dot_data)
Image(graph.create_png())
1043 chars
30 lines

This will create a tree.dot file in the current directory which can be converted to an image using dot command line tool provided by Graphviz. Alternatively, using pydotplus and IPython.display module, you can display the decision tree directly in the notebook. Note that for this to work, you'll need to install Graphviz and pydotplus libraries.

related categories

gistlibby LogSnag