【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('决策树可视化')
相关推荐
涛声依旧-底层原理研究所30 分钟前
残差连接与层归一化通俗易懂的详解
人工智能·python·神经网络·transformer
csdn_aspnet36 分钟前
Python 算法快闪 LeetCode 编号 70 - 爬楼梯
python·算法·leetcode·职场和发展
fantasy_arch1 小时前
pytorch人脸匹配模型
人工智能·pytorch·python
熊猫_豆豆1 小时前
广义相对论水星近日点进动完整详细数学推导
python·天体·广义相对论
web3.08889991 小时前
1688 图搜接口(item_search_img / 拍立淘) 接入方法
开发语言·python
AI算法沐枫2 小时前
深度学习python代码处理科研测序数据
数据结构·人工智能·python·深度学习·决策树·机器学习·线性回归
哥布林学者2 小时前
高光谱拼接算法(一)扫推式成像和航带拼接算法
机器学习·高光谱成像
X1A0RAN3 小时前
解决Pycharm中部分文件或文件夹被隐藏不展示问题
ide·python·pycharm
MomentYY3 小时前
第 3 篇:让 Agent 学会分工,LangGraph 构建多 Agent系统
人工智能·python·agent
程序员Jelena3 小时前
Python 代码是什么?—— 从字节到执行的完整解析
python