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
    点赞
  • 53
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是使用Wine数据集实现adaboost算法Python代码。首先我们需要导入所需的库和数据集: ```python import numpy as np from sklearn.ensemble import AdaBoostClassifier from sklearn.datasets import load_wine from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score wine = load_wine() X = wine.data y = wine.target ``` 接下来,我们将数据集分为训练集和测试集: ```python X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) ``` 然后,我们可以使用`AdaBoostClassifier`类来创建adaboost分类器: ```python ada = AdaBoostClassifier(n_estimators=50, learning_rate=1) ``` 在这里,我们选择了50个基本分类器,并将学习率设置为1。现在,我们可以使用训练数据来训练adaboost分类器: ```python ada.fit(X_train, y_train) ``` 最后,我们可以使用测试数据来评估adaboost分类器的性能: ```python y_pred = ada.predict(X_test) accuracy = accuracy_score(y_test, y_pred) print("Accuracy:", accuracy) ``` 完整的代码如下: ```python import numpy as np from sklearn.ensemble import AdaBoostClassifier from sklearn.datasets import load_wine from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score wine = load_wine() X = wine.data y = wine.target X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) ada = AdaBoostClassifier(n_estimators=50, learning_rate=1) ada.fit(X_train, y_train) y_pred = ada.predict(X_test) accuracy = accuracy_score(y_test, y_pred) print("Accuracy:", accuracy) ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值