转载声明
原文作者:Datawhale学习社区
原文链接:Datawhale学习社区
参考资料:
https://www.cnblogs.com/earendil/p/8872001.html
https://www.zhihu.com/question/26760839/answer/40337791
著作权归作者所有,任何形式的转载都请联系作者。
bagging的算法
从原始样本集中有放回的抽取训练集。每轮从原始样本集中使用Bootstraping的方法抽取n个训练样本,共进行k轮抽取,得到k个训练集。(k个训练集之间是相互独立的)
通过k个样本训练得到k个模型
对分类问题:将上步得到的k个模型采用投票的方式得到分类结果;
对回归问题,计算上述模型的均值作为最后的结果。
bagging的案例分析(基于sklearn,介绍随机森林的相关理论以及实例)
Sklearn为我们提供了 BaggingRegressor 与 BaggingClassifier 两种Bagging方法的API,我们在这里通过一个完整的例子演示Bagging在分类问题上的具体应用。这里两种方法的默认基模型是树模型。
-
Bagging的一个典型应用是随机森林。顾名思义,“森林”是由许多“树”bagging组成的。在具体实现上,用于每个决策树训练的样本和构建决策树的特征都是通过随机采样得到的,随机森林的预测结果是多个决策树输出的组合(投票)。随机森林的示意图如下:
RandomForest.png
-
使用sklearn来实现基于决策树方法的bagging策略。
- 创建一个含有1000个样本20维特征的随机分类数据集:
# test classification dataset from sklearn.datasets import make_classification # define dataset X, y = make_classification(n_samples=1000, n_features=20, n_informative=15, n_redundant=5, random_state=5) # summarize the dataset print(X.shape, y.shape)
- 我们将使用重复的分层k-fold交叉验证来评估该模型,一共重复3次,每次有10个fold。我们将评估该模型在所有重复交叉验证中性能的平均值和标准差。
# evaluate bagging algorithm for classification from numpy import mean from numpy import std from sklearn.datasets import make_classification from sklearn.model_selection import cross_val_score from sklearn.model_selection import RepeatedStratifiedKFold from sklearn.ensemble import BaggingClassifier # define dataset X, y = make_classification(n_samples=1000, n_features=20, n_informative=15,n_redundant=5, random_state=5) # define the model model = BaggingClassifier() # evaluate the model cv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1) n_scores = cross_val_score(model, X, y, scoring='accuracy', cv=cv, n_jobs=-1,error_score='raise') # report performance print('Accuracy: %.3f (%.3f)' % (mean(n_scores), std(n_scores)))