【Python机器学习】构造决策树

通常来说,构造决策树直到所有叶结点都是纯的叶结点,但这会导致模型非常复杂,并且对于训练数据高度过拟合。

为了防止过拟合,有两种常见策略:

1、尽早停止树的生长,也叫预剪枝

2、先构造树,但随后删除或折叠信息量很少的结点,也叫后剪枝。

预剪枝的限制条件可能包含限制树的最大深度、限制叶结点的最大数目、规定一个结点中数据点的最小数目。

如果不防止过拟合:

python 复制代码
from sklearn.tree import DecisionTreeClassifier,export_graphviz
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
from sklearn.datasets import load_breast_cancer
import graphviz


plt.rcParams['font.sans-serif'] = ['SimHei']

cancer=load_breast_cancer()
X_train,X_test,y_train,y_test=train_test_split(
    cancer.data,cancer.target,stratify=cancer.target,random_state=42
)
tree=DecisionTreeClassifier(random_state=0)
tree.fit(X_train,y_train)
print('训练集score:{:.3f}'.format(tree.score(X_train,y_train)))
print('测试集score:{:.3f}'.format(tree.score(X_test,y_test)))

可以看到,训练集上精度是100%,但测试集的精度只有93.7%。

防止过拟合,比如限制决策树的深度为4:

python 复制代码
tree=DecisionTreeClassifier(max_depth=4,random_state=0)

可以看到,虽然训练集的精度下降,但是测试集的精度有所提升。

还可以用tree模块的export_graphviz函数来将树可视化。这个函数会生成一个dot文件,然后用graphviz读取这个文件并可视化(通过生成pdf文件的方式):

python 复制代码
export_graphviz(tree,out_file='tree_1.dot',class_names=['malignant','benigh'],feature_names=cancer.feature_names,impurity=False,filled=True)
with open('tree_1.dot') as f:
    dot_graph=f.read()
g=graphviz.Source(dot_graph)
g.render('决策树可视化')
相关推荐
JavaEdge在掘金4 分钟前
启动nginx报错,80 failed (97: Address family not supported by protocol)
python
纪元A梦11 分钟前
华为OD机试真题——绘图机器(2025A卷:100分)Java/python/JavaScript/C++/C/GO最佳实现
java·javascript·c++·python·华为od·go·华为od机试题
程序员小远23 分钟前
接口测试和单元测试详解
自动化测试·软件测试·python·测试工具·单元测试·测试用例·接口测试
Tech Synapse32 分钟前
电商商品推荐系统实战:基于TensorFlow Recommenders构建智能推荐引擎
人工智能·python·tensorflow
聿小翼35 分钟前
selenium-wire 与 googletrans 的爱恨情仇
python
咖啡调调。37 分钟前
模板引擎语法-算术运算
python·django·sqlite
CodeCraft Studio38 分钟前
Excel处理控件Spire.XLS系列教程:Java设置Excel活动工作表或活动单元格
java·python·excel
Doker 多克38 分钟前
Python-Django系列—部件
开发语言·python
Linux运维老纪40 分钟前
Python文件操作及数据库交互(Python File Manipulation and Database Interaction)
linux·服务器·数据库·python·云计算·运维开发
weixin_4307509341 分钟前
智能小助手部署 Win10 + ollama的Deepseek + CentOS+ maxKB
linux·人工智能·机器学习·语言模型·自然语言处理·centos