In R I can draw a graphical representation of a decision tree corresponding to a CART model directly using an API. For example prp
will produce something like
But I can't find any similar API for the equivalent functionality in Python. For example, as near as I can tell neither sklearn
's RandomForestClassifier
nor DecisionTreeClassifier
have methods or drawing trees.
How can I get a graphical representation of a CART or random forest tree in Python?
The easiest way to plot a decision tree in R is to use the prp() function from the rpart. plot package.
Use the export_graphviz
function.
from sklearn.tree import DecisionTreeClassifier, export_graphviz
np.random.seed(0)
X = np.random.randn(10, 4)
y = array(["foo", "bar", "baz"])[np.random.randint(0, 3, 10)]
clf = DecisionTreeClassifier(random_state=42).fit(X, y)
export_graphviz(clf)
Now dotty tree.dot
should display something like
Here's a notebook.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With