Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I draw a CART tree in Python, as I can in R?

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?

like image 988
orome Avatar asked Apr 02 '14 22:04

orome


People also ask

How do I plot a tree in R?

The easiest way to plot a decision tree in R is to use the prp() function from the rpart. plot package.


1 Answers

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

tree visualization

Here's a notebook.

like image 104
Fred Foo Avatar answered Oct 08 '22 22:10

Fred Foo