【机器学习算法-python实现】Adaboost的实现(1)-单层决策树(decision stump)
生活随笔
收集整理的這篇文章主要介紹了
【机器学习算法-python实现】Adaboost的实现(1)-单层决策树(decision stump)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
(轉(zhuǎn)載請注明出處:http://blog.csdn.net/buptgshengod)
1.背景
? ? ?上一節(jié)學(xué)習(xí)支持向量機(jī),感覺公式都太難理解了,弄得我有點頭大。不過這一章的Adaboost線比較起來就容易得多。Adaboost是用元算法的思想進(jìn)行分類的。什么事元算法的思想呢?就是根據(jù)數(shù)據(jù)集的不同的特征在決定結(jié)果時所占的比重來劃分?jǐn)?shù)據(jù)集。就是要對每個特征值都構(gòu)建決策樹,并且賦予他們不同的權(quán)值,最后集合起來比較。? ? ? 比如說我們可以通過是否有胡子和身高的高度這兩個特征來來決定一個人的性別,很明顯是否有胡子可能在判定性別方面比身高更準(zhǔn)確,所以在判定的時候我們就賦予這個特征更大的權(quán)重,比如說我們把權(quán)重設(shè)成0.8:0.2。這樣就比0.5:0.5的權(quán)重來的更準(zhǔn)確些。
2.構(gòu)建決策樹
? ? 接著我們來構(gòu)建決策樹。我們的決策樹要實現(xiàn)主要兩個功能,一個是找出對結(jié)果影響最大的特征值。另外一個功能是找到這個特征值得閾值。閾值就是,比方說閾值是d,當(dāng)特征值大于d結(jié)果為1,當(dāng)特征值小于d結(jié)果為0。首先看下數(shù)據(jù)集,是一個兩個特征值的矩陣。 ef loadSimpData():datMat = 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 datMat,classLabels
接著是樹的分類函數(shù)。這個函數(shù)在下面的循環(huán)里要用到,作用很簡單,就是比對每一列的特征值和目標(biāo)函數(shù),返回比對的結(jié)果。四個參數(shù)分別是(輸入矩陣,第幾列,閾值,lt或gt) def stumpClassify(dataMatrix,dimen,threshVal,threshIneq):#just classify the dataretArray = ones((shape(dataMatrix)[0],1))if threshIneq == 'lt':retArray[dataMatrix[:,dimen] <= threshVal] = -1.0else:retArray[dataMatrix[:,dimen] > threshVal] = -1.0return retArray
最后是構(gòu)建二叉樹函數(shù),通過循環(huán)比較得到最佳特征值和它的閾值。D是初始矩陣的權(quán)重。
def buildStump(dataArr,classLabels,D):dataMatrix = mat(dataArr); labelMat = mat(classLabels).Tm,n = shape(dataMatrix)numSteps = 10.0; bestStump = {}; bestClasEst = mat(zeros((m,1)))minError = inf #init error sum, to +infinityfor i in range(n):#loop over all dimensionsrangeMin = dataMatrix[:,i].min(); rangeMax = dataMatrix[:,i].max();stepSize = (rangeMax-rangeMin)/numStepsfor j in range(-1,int(numSteps)+1):#loop over all range in current dimensionfor inequal in ['lt', 'gt']: #go over less than and greater thanthreshVal = (rangeMin + float(j) * stepSize)predictedVals = stumpClassify(dataMatrix,i,threshVal,inequal)#call stump classify with i, j, lessThanerrArr = mat(ones((m,1)))errArr[predictedVals == labelMat] = 0weightedError = 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 = weightedErrorbestClasEst = predictedVals.copy()bestStump['dim'] = ibestStump['thresh'] = threshValbestStump['ineq'] = inequalreturn bestStump,minError,bestClasEst
3.結(jié)果
當(dāng)我們假設(shè)初始權(quán)重相同(5行數(shù)據(jù)也就是都是0.2),得到結(jié)果
{'dim': 0, 'ineq': 'lt', 'thresh': 1.3}——第一個特征值權(quán)重最大,閾值是1.3
?[[ 0.2]]——錯誤率0.2,也就是五個錯一個
[[-1.]————判斷結(jié)果,第一個數(shù)據(jù)錯誤
?[ 1.]
?[-1.]
?[-1.]
?[ 1.]]
4.代碼下載
下載地址(Decision Stump)
參考文獻(xiàn):
? ? [1] machine learning in action,Peter Harrington
? ?
總結(jié)
以上是生活随笔為你收集整理的【机器学习算法-python实现】Adaboost的实现(1)-单层决策树(decision stump)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【机器学习算法-python实现】svm
- 下一篇: python 获得github代码库列表