Task05 Bagging

本文介绍了Bootstrap自展法及其在生态学和进化研究中的应用,详细阐述了Bagging(Bootstrap Aggregating)的概念,包括其工作原理和在分类与回归问题中的集成策略。此外,提供了一个Python实现Bagging集成学习方法的示例,展示了如何通过投票法和随机欠采样进行模型训练和预测,并评估模型性能。
摘要由CSDN通过智能技术生成

1、Bootstrap又称自展法,是用小样本估计总体值的一种非参数方法,在进化和生态学研究中应用十分广泛。例如进化树分化节点的自展支持率等。Bootstrap的思想,是生成一系列bootstrap伪样本,每个样本是初始数据有放回抽样。通过对伪样本的计算,获得统计量的分布。例如,要进行1000次bootstrap,求平均值的置信区间,可以对每个伪样本计算平均值。这样就获得了1000个平均值。对着1000个平均值的分位数进行计算, 即可获得置信区间。已经证明,在初始样本足够大的情况下,bootstrap抽样能够无偏得接近总体的分布。

2、bootstrps bagging 他们都属于集成学习方法,(如: Bagging,Boosting,Stacking),将训练的学习器集成在一起,原理来源于PAC学习模型(ProbablyApproximately CorrectK)

bootstraps:名字来自成语“pull up by your ownbootstraps”,意思是依靠你自己的资源,它是一种有放回的抽样方法,学习中还发现有种叫jackknife的方法,它是每一次移除一个样本。

3、bagging: bootstrapaggregating的缩写。让该学习算法训练多轮,每轮的训练集由从初始的训练集中随机取出的n个训练倒组成,初始训练例在某轮训练集中可以出现多次或根本不出现训练之后可得到一个预测函数序列h.,⋯⋯h 最终的预测函数H对分类问题采用投票方式,对回归问题采用简单平均方法对新示例进行判别。

4、集成方法Bagging python实现

import numpy as np
import pandas as pd
from collections import defaultdict 
import random
from sklearn.model_selection import train_test_split
from sklearn.metrics import precision_score, recall_score
from sklearn.ensemble import IsolationForest

class Bagging(object):

    def __init__(self,n_estimators,estimator,rate=1.0):
        self.estimator = estimator
        self.n_estimators = n_estimators
        self.rate = rate

    def Voting(self,data):          #投票法
        term = np.transpose(data)   #转置
        result =list()              #存储结果

        def Vote(df):               #对每一行做投票
            store = defaultdict()
            for kw in df:
                store.setdefault(kw, 0)
                store[kw] += 1
            return max(store,key=store.get)

        result= map(Vote,term)      #获取结果
        return result

    #随机欠采样函数
    def UnderSampling(self,data):
        #np.random.seed(np.random.randint(0,1000))
        data=np.array(data)
        np.random.shuffle(data)    #打乱data          
        newdata = data[0:int(data.shape[0]*self.rate),:]   #切片,取总数*rata的个数,删去(1-rate)%的样本
        return newdata   

    def TrainPredict(self,train,test):          #训练基础模型,并返回模型预测结果
        clf = self.estimator.fit(train[:,0:-1],train[:,-1])
        result = clf.predict(test[:,0:-1])
        return result

    #简单有放回采样
    def RepetitionRandomSampling(self,data,number):     #有放回采样,number为抽样的个数
        sample=[]
        for i in range(int(self.rate*number)):
             sample.append(data[random.randint(0,len(data)-1)])
        return sample

    def Metrics(self,predict_data,test):        #评价函数
        score = predict_data
        recall=recall_score(test[:,-1], score, average=None)    #召回率
        precision=precision_score(test[:,-1], score, average=None)  #查准率
        return recall,precision


    def MutModel_clf(self,train,test,sample_type = "RepetitionRandomSampling"):
        print "self.Bagging Mul_basemodel"
        result = list()
        num_estimators =len(self.estimator)   #使用基础模型的数量

        if sample_type == "RepetitionRandomSampling":
            print "选择的采样方法:",sample_type
            sample_function = self.RepetitionRandomSampling
        elif sample_type == "UnderSampling":
            print "选择的采样方法:",sample_type
            sample_function = self.UnderSampling 
            print "采样率",self.rate
        elif sample_type == "IF_SubSample":
            print "选择的采样方法:",sample_type
            sample_function = self.IF_SubSample 
            print "采样率",(1.0-self.rate)

        for estimator in self.estimator:
            print estimator
            for i in range(int(self.n_estimators/num_estimators)):
                sample=np.array(sample_function(train,len(train)))       #构建数据集
                clf = estimator.fit(sample[:,0:-1],sample[:,-1])
                result.append(clf.predict(test[:,0:-1]))      #训练模型 返回每个模型的输出

        score = self.Voting(result)
        recall,precosoion = self.Metrics(score,test)
        return recall,precosoion   

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值