Issue
I am following a tutorial on using python v3.6 to do decision tree with machine learning using scikit-learn.
Here is the code;
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import mglearn
import graphviz
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
cancer = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(cancer.data, cancer.target, stratify=cancer.target, random_state=42)
tree = DecisionTreeClassifier(random_state=0)
tree.fit(X_train, y_train)
tree = DecisionTreeClassifier(max_depth=4, random_state=0)
tree.fit(X_train, y_train)
from sklearn.tree import export_graphviz
export_graphviz(tree, out_file="tree.dot", class_names=["malignant", "benign"],feature_names=cancer.feature_names, impurity=False, filled=True)
import graphviz
with open("tree.dot") as f:
dot_graph = f.read()
graphviz.Source(dot_graph)
How do I use Graphviz to see what is inside dot_graph? Presumably, it should look something like this;
Solution
graphviz.Source(dot_graph)
returns a graphviz.files.Source
object.
g = graphviz.Source(dot_graph)
use g.render()
to create an image file. When I ran it on your code without an argument I got a Source.gv.pdf
but you can specify a different file name. There is also a shortcut g.view()
, which saves the file and opens it in an appropriate viewer application.
If you paste the code as it is in a rich terminal (such as Spyder/IPython with inline graphics or a Jupyter notebook) it will automagically display the image instead of the object's Python representation.
Answered By - MB-F
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.