《李沐实用机器学习之5.2 Bagging》
slides: https://c.d2l.ai/stanford-cs329p/_static/pdfs/cs329p_slides_7_2.pdf
Bagging - Bootstrap AGGregatING
Learn n base learners in parallel, combine to reduce model variance.
先训练 n 个模型(base learners),每个模型独立训练(parallel)
Combine learners by averaging the outputs (regression) or majority voting (classification)
回归问题:对每个模型的输出做平均;分类问题:投票
Each base learner is trained on a bootstrap sample
- Given a dataset of m examples, create a sample by randomly sampling m examples with replacement # 有放回采样
- Around \(1 − 1/e ≈ 63\%\) unique examples will be sampled use the out-of-bag examples for validation # 剩下 27% 是一些重复样本,没有被采样的数据作为验证集,来检查模型效果。
Bagging Code (scikit-learn)
class Bagging: def __init__(self, base_learner, n_learners): self.learners = [clone(base_learner) for _ in range(n_learners)] def fit(self, X, y): for learner in self.learners: examples = np.random.choice( np.arange(len(X)), int(len(X)), replace=True) # replace=True 有放回采样 learner.fit(X.iloc[examples, :], y.iloc[examples]) def predict(self, X): preds = [learner.predict(X) for learner in self.learners] return np.array(preds).mean(axis=0) # 回归模型做平均
随机森林
使用决策树做 base learners。
经常 有放回采样时候会随机采样一些特征,即 列也会随机采样。好处是:避免一定的过拟合和更大的增加每一颗决策树之间的差异性。
增加 base learners,不会看到泛化误差往上升,因为降低了方差,而没有使得偏差更大。 通常可以增加模型的个数,而不会变差,可能也不会变好。
Apply bagging with unstable Learners
bagging 主要下降方差,方差什么时候下降快?方差比较大的时候,通过取均值,方差下降的比较快。什么时候方差比较大?方差比较大的模型叫做 不稳定模型。
bagging 时候,应该使用 不稳定的模型 作为 base learners。
决策树不是一个稳定的模型,适合做 bagging。
线性回归比较稳定,不适合做 bagging。
总结:
bagging 在数据上使用 Bootstrap(有放回) 采样 训练多个模型。
bagging 用于降低方差,尤其是 base learners 不稳定。最重要的应用是 随机森林。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人