matplotlib可视化决策树
时间: 2023-07-12 15:05:24 浏览: 54
可以使用Graphviz和pydotplus来将决策树可视化。首先需要安装Graphviz和pydotplus:
```
pip installviz
pip install pydotplus
```
然后使用以下代码将决策树可视化```python
from sklearn.tree import DecisionTreeClassifier,_graphviz
from sklearn.datasets import load_iris
import graphviz
import pydotplus
# 加载数据
iris = load_iris()
X = iris.data
y = iris.target
# 训练决策树模型
clf = DecisionTreeClassifier()
clf.fit(X, y)
# 将决策树导出为DOT格式
dot_data = export_graphviz(clf,
out_file=None,
feature_names=iris.feature_names,
class_names=iris.target_names,
filled=True, rounded=True,
special_characters=True)
# 将DOT格式的决策树转换为图形
graph = pydotplus.graph_from_dot_data(dot_data)
graphviz.Source(graph.to_string())
```
这段代码将生成一张决策树图形并在Notebook中显示。如果要保存到文件,可以使用以下代码:
```python
graph.write_png('iris_decision_tree.png')
```