Python决策树的可视化
程序员文章站
2024-03-19 20:56:58
...
方法一:
# Fit the classifier with default hyper-parameters
clf = DecisionTreeClassifier(random_state=1234)
model = clf.fit(X, y)
text_representation = tree.export_text(clf)
print(text_representation)
|--- feature_2 <= 2.45
| |--- class: 0
|--- feature_2 > 2.45
| |--- feature_3 <= 1.75
| | |--- feature_2 <= 4.95
| | | |--- feature_3 <= 1.65
| | | | |--- class: 1
| | | |--- feature_3 > 1.65
| | | | |--- class: 2
| | |--- feature_2 > 4.95
| | | |--- feature_3 <= 1.55
| | | | |--- class: 2
| | | |--- feature_3 > 1.55
| | | | |--- feature_0 <= 6.95
| | | | | |--- class: 1
| | | | |--- feature_0 > 6.95
| | | | | |--- class: 2
| |--- feature_3 > 1.75
| | |--- feature_2 <= 4.85
| | | |--- feature_1 <= 3.10
| | | | |--- class: 2
| | | |--- feature_1 > 3.10
| | | | |--- class: 1
| | |--- feature_2 > 4.85
| | | |--- class: 2
方法二:
from dtreeviz.trees import dtreeviz # remember to load the package
viz = dtreeviz(clf, X, y,
target_name="target",
feature_names=iris.feature_names,
class_names=list(iris.target_names))
viz
方法三:
fig = plt.figure(figsize=(25,20))
_ = tree.plot_tree(clf,
feature_names=iris.feature_names,
class_names=iris.target_names,
filled=True)
2. dict类型的树
import pydot
menu = {'dinner':
{'chicken':'good',
'beef':'average',
'vegetarian':{
'tofu':'good',
'salad':{
'caeser':'bad',
'italian':'average'}
},
'pork':'bad'}
}
def draw(parent_name, child_name):
edge = pydot.Edge(parent_name, child_name)
graph.add_edge(edge)
def visit(node, parent=None):
for k,v in node.iteritems():
if isinstance(v, dict):
# We start with the root node whose parent is None
# we don't want to graph the None node
if parent:
draw(parent, k)
visit(v, k)
else:
draw(parent, k)
# drawing the label using a distinct name
draw(k, k+'_'+v)
graph = pydot.Dot(graph_type='graph')
visit(menu)
graph.write_png('example1_graph.png')
参考: