plot decision tree sklearn python in python

To plot a decision tree built with scikit-learn in Python, we can use the export_graphviz() function from the sklearn.tree module to create a graph of the decision tree, then plot it using the graphviz library.

Here is an example code:

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

# Load dataset
iris = load_iris()

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

# Export decision tree to DOT format
dot_data = export_graphviz(clf, out_file=None,
                           feature_names=iris.feature_names,
                           class_names=iris.target_names,
                           filled=True, rounded=True,
                           special_characters=True)

# Create graph from DOT data
graph = graphviz.Source(dot_data)

# Show graph
graph.render('iris_decision_tree', view=True)
686 chars
24 lines

In this example, we first load the Iris dataset from sklearn.datasets. Then, we train a decision tree classifier on the data using DecisionTreeClassifier().

Next, we use export_graphviz() to create a DOT format representation of the decision tree, and store it in the dot_data variable.

We then create a graphviz.Source object from the DOT data, and use render() to create a PDF file and display it.

This will create a PDF file named "iris_decision_tree.pdf" which shows the visual representation of the decision tree.

gistlibby LogSnag