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

In RI, you can draw a graphical representation of the decision tree corresponding to the CART model directly using the API. For example, will produce something like prp

fMRaE.png

But I cannot find any similar API for equivalent functionality in Python. For example, as far as I can tell, no one sklearn RandomForestClassifierhas methods or drawing trees. DecisionTreeClassifier

How can I get a graphical representation of a CART or random tree of trees in Python?

+5
source share
2 answers

Use the function . export_graphviz

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)

dotty tree.dot -

tree visualization

.

+4

Jupyter:

# Imports
from sklearn.tree import DecisionTreeClassifier, export_graphviz
from sklearn.externals.six import StringIO
from IPython.display import Image, display
import pydotplus

def jupyter_graphviz(m, **kwargs):
    dot_data = StringIO()
    export_graphviz(m, dot_data, **kwargs)
    graph = pydotplus.graph_from_dot_data(dot_data.getvalue())  
    display(Image(graph.create_png()))

:

import sklearn.datasets as datasets
import pandas as pd

iris = datasets.load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
y = iris.target
dtree = DecisionTreeClassifier(random_state=42)
dtree.fit(df, y)

jupyter_graphviz(dtree, filled=True, rounded=True, special_characters=True)

Tree visualization

, .

0

Source: https://habr.com/ru/post/1534731/


All Articles