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.py686 chars24 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