当前位置: 首页 > news >正文

集成学习——Bagging,Boosting

一.什么是集成学习

集成学习的基本思想是通过结合多个基学习器的预测结果,来提高模型的泛化能力和稳定性。这些基学习器可以是相同类型的算法,也可以是不同类型的算法。

当基学习器之间具有一定的差异性时,它们在面对不同的样本子集或特征子集时,可能会犯不同的错误。通过将这些基学习器集成起来,可以相互补充,减少错误,从而提高整体的预测准确性。

二. 集成学习的作用

1.增加准确度:多个模型通常比单个模型预测更准确。

2.减少过拟合:通过模型多样性降低对训练数据特定模式的依赖。

3.对噪声数据和异常数据有更高的容忍度。

三.主要的集成学习方法

1.Bagging

原理:通过自助采样获得多个训练集,分别训练模型,然后取平均值(回归时)或投票(分类时)。

代表算法:随机森林算法。

bagging是一种并行式的集成学习方法,不同训练集训练模型之间没有联系

随机森林:决策树 + Bagging

随机森林api(使用前要记得 from sklearn.ensemble import RandomForestClassifier):

RandomForestClassifier(n_estimators = 40,  #随机森林中决策树的数量,一般在50-100之间criterion = 'gini',  #分割特征的方法max_depth = None,bootstrap = None,random_state = 42  #随机数种子
)

Bagging分类器:

BaggingClassifier(estimator = DecisionTreeClassifier(),  #集成算法使用决策树n_estimators = 60,  #多少个决策树max_samples = 0.8,  #每次采样80%的样本max_features = 0.8,  #每次采样80%的特征random_state = 42  #随机数种子
)

2.Boosting

原理:在每一轮迭代中,根据当前的样本权重分布,训练一个弱学习器。这个弱学习器会尝试对训练数据进行拟合,但它的性能可能相对较弱。然后,根据弱学习器的预测结果,调整样本的权重。具体来说,对于被错误分类的样本,增加其权重;对于被正确分类的样本,降低其权重。这样,在下一轮迭代中,弱学习器会更加关注那些之前被错误分类的样本。这个过程不断重复,直到达到预设的迭代次数或者满足其他停止条件。

代表算法:AdaBoost

Boosting是一种串行集成学习方法,将多个弱学习器集合成一个强学习器。

逐步改进:每个新模型都专注于纠正前一个模型的错误。

加权训练:错误分类的样本在后续训练中获得更高权重。

线性组合:将所有弱学习器的预测结果加权组合。

AdaBoost api(使用前要记得 from sklearn.ensemble import AdaBoostClassifier):

AdaBoostClassifier(estimator = DecisionTreeClassifier(),n_estimators = 60,learning_rate = 0.8,random_state = 42)

四.总结

Bagging:从原始训练数据集中有放回地随机抽样,生成多个子数据集,然后分别在这些子数据集上训练不同的基学习器,最后将这些基学习器的预测结果进行组合(分类任务通常采用投票法,回归任务通常采用平均法)来得到最终的预测结果。

Boosting:在训练过程中,根据前一个基学习器的预测结果来调整样本的权重,使得被错误分类的样本在后续的训练中得到更多的关注,然后依次训练多个基学习器,每个基学习器都在上一轮调整后的样本权重基础上进行训练,最后将这些基学习器按照一定的权重组合起来进行预测。

五.小练习

1.

 

import matplotlib.pyplot as plt
from IPython.core.pylabtools import figsize
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
import numpy as np
import pandas as pdiris = load_iris()x = iris.data
y = iris.targetx_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.3, random_state = 42)
R_forest = RandomForestClassifier(n_estimators = 100,criterion = 'gini',max_depth = 3,random_state = 42
)
R_forest.fit(x_train, y_train)
y_predict = R_forest.predict(x_test)
print('准确率:', accuracy_score(y_predict, y_test))print('分类')
print(classification_report(y_test, y_predict, target_names=iris.target_names))cm = confusion_matrix(y_test, y_predict)
cm_df = pd.DataFrame(cm,index = [f"预测{cls}" for cls in iris.target_names],columns = [f"实际{cls}" for cls in iris.target_names]
)
print(cm_df)plt.figure((figsize(10, 6)))
plt.barh(iris.feature_names, R_forest.feature_importances_)
plt.title('importance')
plt.xlabel('feature_importances')
plt.ylabel('feature_names')
plt.tight_layout()
plt.show()

2.

 

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import classification_report, roc_auc_scoredata = pd.read_csv('creditcard.csv')scaler = StandardScaler()
data['Amount'] = scaler.fit_transform(data['Amount'].values.reshape(-1, 1))# 删除Time列
df = data.drop('Time', axis=1)x = data.drop('Class', axis=1)
y = data['Class']
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=42, stratify=y)# 4. 训练模型
model = RandomForestClassifier(n_estimators=100,class_weight='balanced',random_state=42)
model.fit(x_train, y_train)y_predict = model.predict(x_test)
y_prob = model.predict_proba(x_test)[:, 1]print("分类报告:")
print(classification_report(y_test, y_predict, digits=4))
print(f"AUC-ROC: {roc_auc_score(y_test, y_prob):.4f}")

http://www.xdnf.cn/news/406207.html

相关文章:

  • 一个极简单的 VUE3 + Element-Plus 查询表单展开收起功能组件
  • android studio开发aar插件,并用uniapp开发APP使用这个aar
  • Java面试全记录:Spring Cloud+Kafka+Redis实战解析
  • 关于groom毛发attributes
  • 防火墙安全策略基础配置
  • 学习黑客BitLocker与TPM详解
  • 【大数据】MapReduce 编程--WordCount
  • AI赋能:构建个性化智能学习规划系统
  • Android 中 Handler (创建时)内存泄漏问题及解决方案
  • PDFMathTranslate:科学 PDF 文件翻译及双语对照工具
  • Web4X:站在Web4.0时代的起点,定义AI商业新生态
  • 专业知识的检索过程 stepbystep - 样例
  • ARM-CortexM固件升级相关问题研究
  • 采用AI神经网络降噪算法的通信语音降噪(ENC)模组性能测试和应用
  • 学习笔记:Conda 环境共享
  • 2025年SDK游戏盾技术深度解析:AI赋能下的DDoS/CC攻击防御革命
  • Html5新特性_js 给元素自定义属性_json 详解_浅克隆与深克隆
  • 模型上下文协议(MCP):AI的“万能插座”
  • Halcon案例(一):C#联合Halcon识别路由器上的散热孔
  • 【Vue3】使用vite创建Vue3工程、Vue3基本语法讲解
  • Windows 添加 hosts 映射
  • 零碳园区能源系统-多能互补体系
  • 星海智算云平台部署GPT-SoVITS模型教程
  • 傲云源墅:以五傲价值重构北京主城别墅格局
  • Spring MVC 和 Spring Boot 是如何访问静态资源的?
  • MySQL数据库表的约束
  • 反弹shell再入门
  • MySQL查询优化100条军规
  • 深度解析RagFlow:本地大模型驱动的高效知识库应用搭建指南
  • Java MVC