【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('决策树可视化')
相关推荐
深蓝电商API33 分钟前
Scrapy爬虫限速与并发控制最佳实践
爬虫·python·scrapy
Derrick__134 分钟前
淘宝MD5爬虫
爬虫·python
薛定谔的猫198237 分钟前
llama-index Embedding 落地到 RAG 系统
开发语言·人工智能·python·llama-index
元智启1 小时前
企业AI应用面临“敏捷响应”难题:快速变化的业务与相对滞后的智能如何同步?
人工智能·深度学习·机器学习
nimadan122 小时前
**手机小说扫榜工具2025推荐,精准追踪榜单动态与题材风向
python·智能手机
编程武士2 小时前
Python 各版本主要变化速览
开发语言·python
Hcoco_me2 小时前
大模型面试题63:介绍一下RLHF
人工智能·深度学习·机器学习·chatgpt·机器人
傻啦嘿哟3 小时前
Python中的@property:优雅控制类成员访问的魔法
前端·数据库·python
sky17203 小时前
VectorStoreRetriever 三种搜索类型
python·langchain
旦莫3 小时前
Python测试开发工具库:日志脱敏工具(敏感信息自动屏蔽)
python·测试开发·自动化·ai测试