python决策树画图
时间: 2023-06-30 17:21:17 浏览: 61
要使用Python绘制决策树,可以使用Graphviz和pydotplus这两个库。下面是一个简单的例子:
```python
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier, export_graphviz
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)
graph = pydotplus.graph_from_dot_data(dot_data)
# 将决策树渲染为PDF格式
graph.write_pdf("iris.pdf")
# 将决策树渲染为PNG格式
graph.write_png("iris.png")
# 将决策树渲染为SVG格式
graph.write_svg("iris.svg")
# 在Jupyter notebook中显示决策树
graphviz.Source(dot_data)
```
这段代码会生成三个文件:iris.pdf、iris.png和iris.svg。你可以选择其中一个进行查看。同时,在Jupyter notebook中也可以直接显示决策树。
相关推荐
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)