帮我写一段决策树可视化的代码(要求包含剪枝),分成3类,类与类之间用绿黄灰颜色区分,节点的字体大小为8
时间: 2023-03-13 12:41:20 浏览: 119
# 基于Python的决策树可视化代码(包含剪枝):# 导入所需的库
import numpy as np
from sklearn.datasets import load_iris
import matplotlib.pyplot as plt
from sklearn.tree import DecisionTreeClassifier
from sklearn.tree import export_graphviz# 加载数据
data = load_iris()
X = data.data
y = data.target# 建立决策树模型
clf = DecisionTreeClassifier(criterion='entropy', max_depth=4, min_samples_leaf=2)
clf.fit(X, y)# 绘制决策树
export_graphviz(clf, out_file="iris.dot", feature_names=data.feature_names, filled=True, class_names=['setosa', 'versicolor', 'virginica'], node_ids=True, special_characters=True, rotate=True, impurity=False, round=True, proportion=True)# 颜色设置
cmap = plt.cm.get_cmap('gist_rainbow', 3)# 节点字体大小
plt.rcParams['font.size'] = 8# 绘制决策树
plt.figure(figsize=(10,10), dpi=80)
plot_tree(clf, feature_names=data.feature_names, class_names=data.target_names, filled=True, cmap=cmap)
plt.show()
阅读全文