matplotlib可视化决策树
时间: 2023-07-12 17:05:48 浏览: 94
要使用matplotlib可视化决策树,需要先安装graphviz和pydotplus两个库。可以使用以下命令进行安装:
```
pip install graphviz
pip install pydotplus
```
然后,可以使用以下代码将决策树可视化:
```python
from sklearn.tree import DecisionTreeClassifier
from sklearn.datasets import load_iris
from sklearn import tree
import pydotplus
from IPython.display import Image
import matplotlib.pyplot as plt
iris = load_iris()
X = iris.data[:, :2]
y = iris.target
clf = DecisionTreeClassifier(max_depth=3)
clf.fit(X, y)
dot_data = tree.export_graphviz(clf, out_file=None,
feature_names=iris.feature_names[:2],
class_names=iris.target_names,
filled=True, rounded=True,
special_characters=True)
graph = pydotplus.graph_from_dot_data(dot_data)
Image(graph.create_png())
plt.figure(figsize=(20,10))
plt.imshow(plt.imread(graph.create_png()),interpolation='nearest')
plt.axis('off')
plt.show()
```
其中,需要将决策树的文本形式转化为图形形式,使用pydotplus库;使用matplotlib库展示决策树。
阅读全文
相关推荐
















