0
  • 聊天消息
  • 系统消息
  • 评论与回复
登录后你可以
  • 下载海量资料
  • 学习在线课程
  • 观看技术视频
  • 写文章/发帖/加入社区
创作中心

完善资料让更多小伙伴认识你,还能领取20积分哦,立即完善>

3天内不再提示

adaboost运行函数的算法怎么来的?基本程序代码实现详细

lviY_AI_shequ 2018-07-21 10:18 次阅读

一.Adaboost理论部分

1.1 adaboost运行过程

注释:算法是利用指数函数降低误差,运行过程通过迭代进行。其中函数的算法怎么来的,你不用知道!当然你也可以尝试使用其它的函数代替指数函数,看看效果如何。

1.2 举例说明算法流程

1.3 算法误差界的证明

注释:误差的上界限由Zm约束,然而Zm又是由Gm(xi)约束,所以选择适当的Gm(xi)可以加快误差的减小。

二.代码实现

2.1程序流程图

2.2基本程序实现

注释:真是倒霉玩意,本来代码全部注释好了,突然Ubuntu奔溃了,全部程序就GG了。。。下面的代码就是官网的代码,部分补上注释。现在使用Deepin桌面版了,其它方面都比Ubuntu好,但是有点点卡。

from numpy import *

def loadDataSet(fileName): #general function to parse tab -delimited floats

numFeat = len(open(fileName).readline().split(' ')) #get number of fields

dataMat = []; labelMat = []

fr = open(fileName)

for line in fr.readlines():

lineArr =[]

curLine = line.strip().split(' ')

for i in range(numFeat-1):

lineArr.append(float(curLine[i]))

dataMat.append(lineArr)

labelMat.append(float(curLine[-1]))

return dataMat,labelMat

def stumpClassify(dataMatrix,dimen,threshVal,threshIneq):#just classify the data

retArray = ones((shape(dataMatrix)[0],1))

if threshIneq == 'lt':

retArray[dataMatrix[:,dimen] <= threshVal] = -1.0

else:

retArray[dataMatrix[:,dimen] > threshVal] = -1.0

return retArray

def buildStump(dataArr,classLabels,D):

dataMatrix = mat(dataArr); labelMat = mat(classLabels).T

m,n = shape(dataMatrix)

numSteps = 10.0; bestStump = {}; bestClasEst = mat(zeros((m,1)))

minError = inf #init error sum, to +infinity

for i in range(n):#loop over all dimensions

rangeMin = dataMatrix[:,i].min(); rangeMax = dataMatrix[:,i].max();

stepSize = (rangeMax-rangeMin)/numSteps

for j in range(-1,int(numSteps)+1):#loop over all range in current dimension

for inequal in ['lt', 'gt']: #go over less than and greater than

threshVal = (rangeMin + float(j) * stepSize)

predictedVals = stumpClassify(dataMatrix,i,threshVal,inequal)#call stump classify with i, j, lessThan

errArr = mat(ones((m,1)))

errArr[predictedVals == labelMat] = 0

weightedError = D.T*errArr #calc total error multiplied by D

#print "split: dim %d, thresh %.2f, thresh ineqal: %s, the weighted error is %.3f" % (i, threshVal, inequal, weightedError)

if weightedError < minError:

minError = weightedError

bestClasEst = predictedVals.copy()

bestStump['dim'] = i

bestStump['thresh'] = threshVal

bestStump['ineq'] = inequal

return bestStump,minError,bestClasEst

def adaBoostTrainDS(dataArr,classLabels,numIt=40):

weakClassArr = []

m = shape(dataArr)[0]

D = mat(ones((m,1))/m) #init D to all equal

aggClassEst = mat(zeros((m,1)))

for i in range(numIt):

bestStump,error,classEst = buildStump(dataArr,classLabels,D)#build Stump

#print "D:",D.T

alpha = float(0.5*log((1.0-error)/max(error,1e-16)))#calc alpha, throw in max(error,eps) to account for error=0

bestStump['alpha'] = alpha

weakClassArr.append(bestStump) #store Stump Params in Array

#print "classEst: ",classEst.T

expon = multiply(-1*alpha*mat(classLabels).T,classEst) #exponent for D calc, getting messy

D = multiply(D,exp(expon)) #Calc New D for next iteration

D = D/D.sum()

#calc training error of all classifiers, if this is 0 quit for loop early (use break)

aggClassEst += alpha*classEst

#print "aggClassEst: ",aggClassEst.T

aggErrors = multiply(sign(aggClassEst) != mat(classLabels).T,ones((m,1)))

errorRate = aggErrors.sum()/m

print ("total error: ",errorRate)

if errorRate == 0.0: break

return weakClassArr,aggClassEst

def adaClassify(datToClass,classifierArr):

dataMatrix = mat(datToClass)#do stuff similar to last aggClassEst in adaBoostTrainDS

m = shape(dataMatrix)[0]

aggClassEst = mat(zeros((m,1)))

for i in range(len(classifierArr)):

classEst = stumpClassify(dataMatrix,classifierArr[i]['dim'],

classifierArr[i]['thresh'],

classifierArr[i]['ineq'])#call stump classify

aggClassEst += classifierArr[i]['alpha']*classEst

#print aggClassEst

return sign(aggClassEst)

def plotROC(predStrengths, classLabels):

import matplotlib.pyplot as plt

cur = (1.0,1.0) #cursor

ySum = 0.0 #variable to calculate AUC

numPosClas = sum(array(classLabels)==1.0)#标签等于1的和(也等于个数)

yStep = 1/float(numPosClas); xStep = 1/float(len(classLabels)-numPosClas)

sortedIndicies = predStrengths.argsort()#get sorted index, it's reverse

sortData = sorted(predStrengths.tolist()[0])

fig = plt.figure()

fig.clf()

ax = plt.subplot(111)

#loop through all the values, drawing a line segment at each point

for index in sortedIndicies.tolist()[0]:

if classLabels[index] == 1.0:

delX = 0; delY = yStep;

else:

delX = xStep; delY = 0;

ySum += cur[1]

#draw line from cur to (cur[0]-delX,cur[1]-delY)

ax.plot([cur[0],cur[0]-delX],[cur[1],cur[1]-delY], c='b')

cur = (cur[0]-delX,cur[1]-delY)

ax.plot([0,1],[0,1],'b--')

plt.xlabel('False positive rate'); plt.ylabel('True positive rate')

plt.title('ROC curve for AdaBoost horse colic detection system')

ax.axis([0,1,0,1])

plt.show()

print ("the Area Under the Curve is: ",ySum*xStep)

注释:重点说明一下非均衡分类的图像绘制问题,想了很久才想明白!

都是相对而言的,其中本文说的曲线在左上方就为好,也是相对而言的,看你怎么定义个理解!

声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉
  • 算法
    +关注

    关注

    23

    文章

    4455

    浏览量

    90750
  • 代码
    +关注

    关注

    30

    文章

    4555

    浏览量

    66750

原文标题:《机器学习实战》AdaBoost算法(手稿+代码)

文章出处:【微信号:AI_shequ,微信公众号:人工智能爱好者社区】欢迎添加关注!文章转载请注明出处。

收藏 人收藏

    评论

    相关推荐

    mini57系列运行算法库的程序,编译没有错误但无法运行是为什么?

    我用mini57系列的芯片跑做一个心率检测的产品。加入心率算法库后,发现程序无法运行,但是编译没有报错。我在线仿真发现无法进入main函数程序
    发表于 01-15 08:33

    一个c源程序至少包括一个函数

    一个C源程序至少包括一个函数。 C语言是一种广泛应用于嵌入式系统和操作系统的程序设计语言。它的基本构造块是函数函数在C语言中扮演着非常重要
    的头像 发表于 11-26 09:01 570次阅读

    c语言中函数函数体用什么符号括起来

    函数 是指将一组能完成一个功能或多个功能的语句放在一起的 代码结构 。 在 C语言程序 中,至少会包含一个函数,及主函数main()。本文将
    的头像 发表于 11-24 15:52 309次阅读
    c语言中<b class='flag-5'>函数</b>的<b class='flag-5'>函数</b>体用什么符号括起来

    python运行一次自动再次运行

    自动化是现代计算机科学和软件开发的一个重要领域。在Python中,有许多方法可以实现自动运行程序的功能。本文将详细介绍如何使用Python实现自动
    的头像 发表于 11-23 15:52 507次阅读

    一分钟带你了解TSMaster小程序编辑代码智能提示功能

    本文给大家带来TSMaster小程序编辑的新功能,其中主要包含:代码编辑智能提示功能、可用外部代码编辑器编辑小程序代码并同步。本文关键字:C小程序
    的头像 发表于 10-28 08:22 1216次阅读
    一分钟带你了解TSMaster小<b class='flag-5'>程序</b>编辑<b class='flag-5'>代码</b>智能提示功能

    静态代码块、构造代码块、构造函数及普通代码块的执行顺序

    时机 静态代码块在类被加载的时候就运行了,而且只运行一次,并且优先于各种代码块以及构造函数。如果一个类中有多个静态
    的头像 发表于 10-09 15:40 432次阅读
    静态<b class='flag-5'>代码</b>块、构造<b class='flag-5'>代码</b>块、构造<b class='flag-5'>函数</b>及普通<b class='flag-5'>代码</b>块的执行顺序

    python函数函数之间的调用

    函数函数之间的调用 3.1 第一种情况 程序代码如下: def x ( f ): def y (): print ( 1 ) return y def f (): print
    的头像 发表于 10-04 17:17 351次阅读

    在STM32单片机上运行除零运算的C程序代码时为何程序不崩溃?

    众所周知,在 C 语言中,当一个数除以0的时候,会导致除法运算异常。程序也会因此崩溃。 为了避免程序崩溃,我们需要在代码中包含对 0 的判断。
    的头像 发表于 09-14 11:11 907次阅读
    在STM32单片机上<b class='flag-5'>运行</b>除零运算的C<b class='flag-5'>程序代码</b>时为何<b class='flag-5'>程序</b>不崩溃?

    如何使用GPIO模仿SPI函数

    应用程序:本文件描述如何使用 GPIO 模仿 SPI 函数 。 BSP 版本: M480系列 BSP CMSIS v3.03.000 硬件: NuMaker-ETM-M487 v1.1 此示例
    发表于 08-31 10:17

    mini57系列运行算法库的程序,编译没有错误但无法运行是为什么?

    我用mini57系列的芯片跑做一个心率检测的产品。加入心率算法库后,发现程序无法运行,但是编译没有报错。我在线仿真发现无法进入main函数程序
    发表于 08-22 08:16

    用于程序代码可视化和监控的对象连接到控制程序

    简介 在此示例中,将用于程序代码可视化和监控的对象连接到控制程序。您先前已在 STEP 7 中创建了一个程序(用于运输传送带上的生产单位)。您还创建了一个 ProDiag 函数块,在其
    的头像 发表于 08-21 10:11 759次阅读
    用于<b class='flag-5'>程序代码</b>可视化和监控的对象连接到控制<b class='flag-5'>程序</b>

    西门子博途SCL:REGION:构建程序代码的步骤

    可以使用指令“构建程序代码”,在 SCL 块中构建程序代码并将其分为几个不同区域。
    的头像 发表于 07-31 09:09 4145次阅读

    Cortex-M0/M4芯片是否支持代码保护用户的程序代码吗?

    NuMicro™ Cortex-M0/M4芯片是否支持代码保护用户的程序代码吗?如何解开LOCK位上的用户配置字?
    发表于 06-19 06:02

    main函数不一定就是程序入口

    写个测试代码代码中有main函数,也有test函数,test就是刚才我们说的入口,不过得指定退出方式,要不然程序
    的头像 发表于 06-15 17:12 421次阅读

    mini57系列运行算法库的程序,编译没有错误,但无法运行是为什么?

    我用mini57系列的芯片跑做一个心率检测的产品。加入心率算法库后,发现程序无法运行,但是编译没有报错。我在线仿真发现无法进入main函数程序
    发表于 06-13 09:05