python决策树可视化完整代码
时间: 2024-10-16 07:02:11 浏览: 35
Python决策树可视化代码.zip
5星 · 资源好评率100%
在Python中,我们可以使用`sklearn`库中的`DecisionTreeClassifier`创建决策树模型,并结合一些可视化工具如`graphviz`(用于生成图形)、`matplotlib`等来展示决策树的结构。以下是一个完整的示例代码:
```python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.tree import export_graphviz
# 加载鸢尾花数据集
iris = load_iris()
X = iris.data
y = iris.target
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 创建决策树分类器
tree_clf = DecisionTreeClassifier(random_state=42)
tree_clf.fit(X_train, y_train)
# 导出决策树到dot文件
export_graphviz(tree_clf,
out_file='iris_tree.dot',
feature_names=iris.feature_names,
class_names=iris.target_names,
filled=True, rounded=True, special_characters=True)
# 使用graphviz将dot转换为图片
from graphviz import Source
with open('iris_tree.dot') as f:
dot_data = f.read()
Source(dot_data).view()
# 可视化结果
plt.figure(figsize=(15, 10))
plot_tree = tree.plot_tree(tree_clf, filled=True, fontsize=12)
plt.show()
#
阅读全文