码迷,mamicode.com
首页 > 编程语言 > 详细

Adaboost的python实现

时间:2019-12-11 23:29:35      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:大于   估计   style   函数   pen   exp   类信息   误差   class类   

不要总是掉包欧,真的丢人啊,一起码起来!

‘‘‘
函数的功能:单层决策树分类函数
参数说明:
xMat:数据矩阵
i:第i列,第几个特征
Q:阈值
返回分类结果:
re
‘‘‘
import numpy as np
import pandas as pd

def classify0(xMat,i,Q,S):
re = np.ones((xMat.shape[0],1))
if S == ‘lt‘:
re[xMat[:,i]<= Q] = -1
else:
re[xMat[:, i] >Q] = -1
return re

‘‘‘
函数功能:找到数据集上最佳的单层决策树
xMat:特征矩阵
yMat:标签矩阵
D:样本权重
返回:
beststump:最佳单层决策树信息
minE:最小误差
bestClas:最佳的分类结果
‘‘‘
def get_Stump(xMat,yMat,D):
m,n = xMat.shape #m为样本数,n为特征数
Steps = 10 #初始化一个步长
bestStump = {} #用字典的形式存储树桩信息
bestClas = np.mat(np.zeros((m,1))) #初始化分类结果为1
minE = np.Inf
for i in range(-1,n): #遍历所有特征
Min = xMat[:,i].min() #找到特征中最小的值
Max = xMat[:,i].max() #找到特征中最大的值
stepSize = (Max-Min)/Steps #计算步长
for j in range(-1,int(Steps)+1): #
for S in [‘lt‘,‘gt‘]: #大于或者小于的情况下
Q = (Min+j*stepSize) #计算阈值
re = classify0(xMat,i,Q,S) #计算分类结果
err = np.mat(np.ones((m,1)))
err[re==yMat]=0 #分类正确的赋值为0
eca = D.T*err #计算误差
if eca<minE: #找到误差最小的分类方式
minE = eca
bestClas = re.copy()
bestStump[‘特征列‘]=i
bestStump[‘阈值‘] = Q
bestStump[‘标志‘] = S
return bestStump,minE,bestClas
xMat = np.matrix([[1,2.1],[1.5,1.6],[1.3,1],[1,1],[2,1]])
yMat = np.matrix([[1],[1],[-1],[-1],[1]])
#print(yMat.shape)
m = xMat.shape[0]
D = np.mat(np.ones((m,1))/m)
bestStump,minE,bestClas = get_Stump(xMat,yMat,D)
#print(bestStump)
#print(minE)
#print(bestClas)
‘‘‘
函数功能:
maxC为最大迭代次数
weakClass弱分类信息
aggClass类别估计值
‘‘‘
def adaboost(xMat,yMat,maxC=4):
weakClass = []
m = xMat.shape[0]
D = np.mat(np.ones((m,1))/m) #初始化权重
aggClass = np.mat(np.zeros((m,1)))
for i in range(maxC):
Stump,error,bestClas = get_Stump(xMat,yMat,D) #构建单层分类器
alpha = float(0.5*np.log((1-error)/max(error,1e-6))) #计算弱分类器的权重衰减 max(error,1e-6)让坟墓不等于0
Stump[‘alpha‘] = np.round(alpha,2) #存储弱学习算法的权重,保留两位小数
weakClass.append(Stump) #存储单层决策树
expon = np.multiply(-1*alpha*yMat,bestClas)
D = np.multiply(D,np.exp(expon))
D = D/D.sum() #更新样本权重
aggClass+= alpha+bestClas #更新累计类别的统计值
aggErr = np.multiply(np.sign(aggClass)!=yMat,np.ones((m,1)))
errRate = aggErr.sum()/m
if errRate==0:break #误差为0 推出循环
return weakClass,aggClass

weakClass,aggClass = adaboost(xMat,yMat,maxC=4)
print(weakClass)
print(aggClass)








Adaboost的python实现

标签:大于   估计   style   函数   pen   exp   类信息   误差   class类   

原文地址:https://www.cnblogs.com/limingqi/p/12026397.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!