Adaboost算法+python源码

1.Adaboost概念

 AdaBoost算法(Adaptive Boosting)是一种有效而实用的Boosting算法,它以一种高度自适应的方法顺序地训练弱学习器。AdaBoost根据前一次的分类效果调整数据的权重,上一个弱学习器中错误分类样本的权重会在下一个弱学习器中增加,正确分类样本的权重会相应减少,并且在每一轮迭代时会向模型加入一个新的弱学习器。不断重复调整权重和训练弱学习器的过程,直到误分类数低于预设值或迭代次数达到指定最大迭代次数时,我们会得到一个强分类器。

算法核心思想如下:在步骤1中先切一刀划分类别,此时将小三角形错误的划分到了圆形类别中,在步骤2便调整这一分类错误的三角形的权重,因此重新分类时,它便能准确的分类到三角形类别。

具体步骤如下下:

 

2. Adaboost算法流程图如下:

 Adaboost算法流程:

 

 

3.数学原理举例

x

1

2

3

4

5

y

1

1

-1

1

-1

 

 

 

 

 

 

 

 

 

 

 

 

4.实验源码

 

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

from sklearn.ensemble import AdaBoostClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.datasets import make_gaussian_quantiles

# 创建数据 高斯数据集 cov方差 std标准差  mean均值 默认值0
x1, y1 = make_gaussian_quantiles(cov=2.,
                              n_samples=200, n_features=2,
                              n_classes=2, random_state=1)
x2, y2 = make_gaussian_quantiles(mean=(3, 3), cov=1.5,
                              n_samples=200, n_features=2,
                              n_classes=2, random_state=1)
print(x1.shape, y1.shape)
print(x2.shape, y2.shape)

X = np.concatenate((x1, x2))
y = np.concatenate((y1, -y2 + 1))
print(X.shape, y.shape)

# 构建adaboost模型
bdt = AdaBoostClassifier(DecisionTreeClassifier(max_depth=1),
                       n_estimators=200)
# 数据量大的时候 可以增加内部分类器的树深度 也可以不限制树深
# max depth树深 数据量大的时候 一般范围在10-100之间
# 数据量小的时候 一般可以设置树深度较小  或者n_estimators较小

# n_estimators迭代次数或者最大弱分类器数: 200次
# base estimators:decisiontreeclassifier选择弱分类器 默认是cart树
# algorithm运算方式:samme 和 samme。r 运算规则 后者。r的是real的算法 以概率调整权重()迭代速度快更快找到最优的
#需要能计算概率的分类器支持
# learning rate:0《v《=1 默认为1 正则项 衰减指数 默认是1可以调小 就是在更新样本权重的时候不要变化太快
# loss:linear。squar ex品ential  误差计算公式 一般用linear足够 回归问题才有 误差率的表示方式
bdt.fit(X, y)
# 准备画图
plot_step = 0.02
x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1
x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1
# 网格 背景区域
xx, yy = np.meshgrid(np.arange(x1_min, x1_max, plot_step),
                     np.arange(x2_min, x2_max, plot_step))
# 预测
Z = bdt.predict(np.c_[xx.ravel(), yy.ravel()])
# 设置维度
Z = Z.reshape(xx.shape)
# 画图
plot_colors = "br"
class_names = "AB"
plt.figure(figsize=(10, 5), facecolor='w')
# 局部子图
# 121表示:在1行2列里面 最后一个1表示地一个位置 第一个子图
plt.subplot(121)
# 画第一个子图的 分类区域
plt.pcolormesh(xx, yy, Z, shading='auto', cmap=plt.cm.Paired)
for i, n, c in zip(range(2), class_names, plot_colors ):
    idx = np.where(y == i)
    # 散点图
    plt.scatter(X[idx, 0], X[idx, 1], c=c, cmap=plt.cm.Paired, label=u"类别%s" % n)
plt.xlim(x1_min, x1_max)
plt.ylim(x2_min, x2_max)
plt.legend(loc='upper right')
plt.xlabel('x1')
plt.ylabel('x2')
plt.title(u'AdaBoost算法分类,正确率为: %.2f%%' % (bdt.score(X, y) * 100))

# 获取决策函数的数值
# 决策函数 最终的 200个弱 学习器融合之后的 计算所有样本的预测值
twoclass_output = bdt.decision_function(X)
print('获取决策函数的数值:', twoclass_output)
print('获取决策函数的数值长度:', len(twoclass_output))
# 获取范围
plot_range = (twoclass_output.min(), twoclass_output.max())

# 122表示: 在1行2列里面 最后一个2表示在第二个位置 第二个子图
plt.subplot(122)
for i, n, c in zip(range(2), class_names, plot_colors ):
#直方图
     plt.hist(twoclass_output[y == i],
              bins=20,
              range=plot_range,
              facecolor=c,
              label=u'类别 %s' % n,
              alpha=.5)
x1, x2, y1, y2 = plt.axis()
plt.axis((x1, x2, y1, y2 * 1.2))
plt.legend(loc='upper right')
plt.ylabel(u'样本数')
plt.xlabel(u'决策函数值')
plt.title(u'Adaboost的决策值')
plt.tight_layout()
plt.subplots_adjust(wspace=0.35)
plt.show()




结果:

 5.优缺点

 优点: 可以处理连续值和离散值 不会出现过拟合现象 模型的鲁棒性比较强 解释强,结构简单

 缺点: 对异常样本敏感,异常样本可能会在迭代过程中获得较高的权重值,最终影响模型效果

  • 5
    点赞
  • 50
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
下面是一个简单的Adaboost算法Python代码示例: ``` python from numpy import * def loadSimpData(): dataMat = matrix([[1. ,2.1], [2. ,1.1], [1.3,1. ], [1. ,1. ], [2. ,1. ]]) classLabels = [1.0, 1.0, -1.0, -1.0, 1.0] return dataMat,classLabels def stumpClassify(dataMatrix,dimen,threshVal,threshIneq): 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 for i in range(n): rangeMin = dataMatrix[:,i].min() rangeMax = dataMatrix[:,i].max() stepSize = (rangeMax-rangeMin)/numSteps for j in range(-1,int(numSteps)+1): for inequal in ['lt', 'gt']: threshVal = (rangeMin + float(j) * stepSize) predictedVals = stumpClassify(dataMatrix,i,threshVal,inequal) errArr = mat(ones((m,1))) errArr[predictedVals == labelMat] = 0 weightedError = D.T*errArr 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) aggClassEst = mat(zeros((m,1))) for i in range(numIt): bestStump,error,classEst = buildStump(dataArr,classLabels,D) alpha = float(0.5*log((1.0-error)/max(error,1e-16))) bestStump['alpha'] = alpha weakClassArr.append(bestStump) expon = multiply(-1*alpha*mat(classLabels).T,classEst) D = multiply(D,exp(expon)) D = D/D.sum() aggClassEst += alpha*classEst aggErrors = multiply(sign(aggClassEst) != mat(classLabels).T,ones((m,1))) errorRate = aggErrors.sum()/m if errorRate == 0.0: break return weakClassArr,aggClassEst dataMat,classLabels = loadSimpData() classifierArray,aggClassEst = adaBoostTrainDS(dataMat,classLabels) print(classifierArray) ``` 该代码实现了简单数据集的Adaboost算法,其中buildStump函数实现了弱分类器的构建,adaBoostTrainDS函数实现Adaboost模型的训练。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值