鱼C论坛

 找回密码
 立即注册
查看: 2534|回复: 1

[技术交流] python实现AdaBoost【分类】

[复制链接]
发表于 2020-11-12 15:53:49 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
参考书籍:《机器学习实战》


  1. import numpy as np

  2. def loadSimpData():
  3.     datMat = np.matrix([[1, 2.1], [2, 1.1], [1.3, 1], [1, 1], [2, 1]])
  4.     classLabels = [1, 1, -1, -1, 1]
  5.     return datMat, classLabels

  6. def stumpClassify(dataMatrix, dimen, threshVal, threshIneq):
  7.     retArray = np.ones((np.shape(dataMatrix)[0], 1))
  8.     if threshIneq == "It":
  9.         retArray[dataMatrix[:, dimen] <= threshVal] = -1
  10.     else:
  11.         retArray[dataMatrix[:, dimen] > threshVal] = -1
  12.     return retArray

  13. def buildStump(dataArr, classLabels, D):#D是定义的权重向量
  14.     dataMatrix = np.mat(dataArr)
  15.     labelMat = np.mat(classLabels).T
  16.     m, n = np.shape(dataMatrix)
  17.     numSteps = 10
  18.     bestStump = {}
  19.     bestClassEst = np.mat(np.zeros((m, 1)))
  20.     minError = np.inf
  21.     for i in range(n):#特征循环
  22.         rangeMin = dataMatrix[:, i].min()#特征中的最小
  23.         rangeMax = dataMatrix[:, i].max()
  24.         stepSize = (rangeMax - rangeMin) / numSteps
  25.         for j in range(-1, int(numSteps) + 1):#特征中按照跨度选取的每个连续特征的值(未来找特征最好切割点)
  26.             for inequal in ['It', 'gt']:
  27.                 threshVal = (rangeMin + float(j) * stepSize)
  28.                 predictedVals = stumpClassify(dataMatrix, i, threshVal, inequal)
  29.                 errArr = np.mat(np.ones((m, 1)))
  30.                 errArr[predictedVals == labelMat] = 0
  31.                 weightedError = D.T * errArr
  32.                 if weightedError < minError:
  33.                     minError = weightedError
  34.                     bestClassEst = predictedVals.copy()
  35.                     bestStump["dim"] = i
  36.                     bestStump["thresh"] = threshVal
  37.                     bestStump["ineq"] = inequal
  38.     return bestStump, minError, bestClassEst

  39. def adaBoostTrainDS(dataArr, classLabels, numIt = 40):
  40.     weakClassArr = []
  41.     m = np.shape(dataArr)[0]
  42.     D = np.mat(np.ones((m, 1)) / m)#每个样本的初始化权重是相同的
  43.     aggClassEst = np.mat(np.zeros((m, 1)))
  44.     for i in range(numIt):
  45.         bestStump, error, classEst = buildStump(dataArr, classLabels, D)
  46.         print("D:", D.T)
  47.         alpha = float(0.5 * np.log((1 - error) / max(error, 1e-16)))#更新每个分类器的权重alpha
  48.         bestStump['alpha'] = alpha#记录每个分类器的alpha值(这个分类器是指针对当前数据集最好的特征划分)
  49.         weakClassArr.append(bestStump)
  50.         print("classEst:", classEst.T)
  51.         #np.mat和np.matrix的区别
  52.         #https://blog.csdn.net/qq_43212169/article/details/101679293
  53.         expon = np.multiply(-1 * alpha * np.mat(classLabels).T, classEst)
  54.         D = np.multiply(D, np.exp(expon))
  55.         D = D / D.sum()
  56.         aggClassEst += alpha * classEst#记录每个数据点的类别估计累计值
  57.         print("aggClassEst:", aggClassEst.T)
  58.         arrErrors = np.multiply(np.sign(aggClassEst) != np.mat(classLabels).T,
  59.                                 np.ones((m, 1)))
  60.         errorRate = arrErrors.sum() / m
  61.         print("total error:", errorRate, "\n")
  62.         if errorRate == 0:
  63.             break
  64.     return weakClassArr


  65. #利用多个弱分类器做最终的分类
  66. def adaClassify(dataToClass, classifierArr):
  67.     dataMatrix = np.mat(dataToClass)
  68.     m = np.shape(dataMatrix)[0]
  69.     aggClassEst = np.mat(np.zeros((m, 1)))
  70.     for i in range(len(classifierArr)):
  71.         classEst = stumpClassify(dataMatrix, classifierArr[i]["dim"],
  72.                                  classifierArr[i]["thresh"],
  73.                                  classifierArr[i]["ineq"])
  74.         aggClassEst += classifierArr[i]["alpha"] * classEst
  75.         print(aggClassEst)
  76.     return np.sign(aggClassEst)
  77.    
  78. datMat, classLabels = loadSimpData()
  79. classifierArray = adaBoostTrainDS(datMat, classLabels)
  80. adaClassify([0, 0],classifierArray)#返回[0,0]特征向量的预测值
复制代码

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2020-11-12 15:54:50 | 显示全部楼层
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-5-20 06:08

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表