可以使用matplotlib库绘制决策树结构或者特征重要性图
时间: 2024-06-09 09:11:39 浏览: 107
是的,可以使用matplotlib库绘制决策树结构或者特征重要性图。以下是使用sklearn库中的RandomForestClassifier模型为例,演示如何绘制特征重要性图:
```python
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
import matplotlib.pyplot as plt
# 加载数据集
iris = load_iris()
X = iris.data
y = iris.target
# 构建模型
rfc = RandomForestClassifier(n_estimators=100, random_state=0)
rfc.fit(X, y)
# 绘制特征重要性图
importances = rfc.feature_importances_
indices = np.argsort(importances)[::-1]
plt.figure(figsize=(10, 6))
plt.title("Feature importances")
plt.bar(range(X.shape[1]), importances[indices])
plt.xticks(range(X.shape[1]), iris.feature_names[indices], rotation=90)
plt.show()
```
运行代码后,将会得到如下图所示的特征重要性图:

如果想要绘制决策树结构,可以使用sklearn库中的export_graphviz方法将树结构输出为DOT格式,并使用graphviz库将其转化为图片。以下是一个示例代码:
```python
from sklearn.tree import export_graphviz
import graphviz
# 将第一棵树输出为DOT格式
dot_data = export_graphviz(rfc.estimators_[0], out_file=None,
feature_names=iris.feature_names,
class_names=iris.target_names,
filled=True, rounded=True,
special_characters=True)
# 将DOT格式转化为图片并显示
graph = graphviz.Source(dot_data)
graph
```
运行代码后,将会得到如下的决策树结构图:

希望这个示例能帮助到你。
阅读全文
相关推荐

















