The initial idea is to combine different classification algorithms to give comprehensive results, which will be more accurate.
Called ensemble methods or meta-algorithms, integrated method or meta Algorithm
There are many integration methods, which can be between different algorithms, or the same algorithm but between different parameter settings. It can also be divided into multiple datasets and distributed between different classifiers.
In general, there are three dimensions for integration, algorithms, algorithm parameters, and datasets.
The following describes two popular metadatabase ideas,
1. Building classifiers from randomly resampled data: Bagging
Bagging is also called Bootstrap aggregating.
The idea is relatively simple. Perform n sampling times for the training set whose size is N, and create a new training set whose size is still n.
Because random sampling is put back, there may be duplicates in the new training set. In some training sets, there will be no new training sets in the samples.
This method is used to generate s new training sets. The same classification algorithm can generate s classifiers with different parameters.
When used, let S classifier, a majority vote to determine the final classification result
Typical bagging algorithms, such as random forest (random forest)
First, bootstrap sampling is used to generate a decision tree using a new training set, and no samples are sampled in the new training set as the test set.
If there are s new training sets, s decision trees will be generated.
The so-called random: first, the new training set is produced by random sampling.
Furthermore, when training a decision tree, each tree node selects M features randomly (M <m total number of features)
Reference, http://zh.wikipedia.org/wiki/%E9%9A%8F%E6%9C%BA%E6%A3% AE %E6%9E%97
2. Boosting
Next we will introduce the most popular AdaBoost Algorithm in boosting. Here we will introduce the implementation. For theoretical reference, refer to the previous article.
We use a single-layer decision tree, that is, demo-stump decision tree as a weak classifier.
The so-called demo-stump is a single-node decision tree that only divides one feature once.
This weak classifier is simple enough, but it is useless if used directly,
For example, for the very simple training set below, a demo-stump cannot be completely correctly classified. Try to make a division on the X or Y axis.
Although the classification cannot be completely correct, we need to find the demo-stump with the smallest error.
The method is very simple. In the range of X and Y, the comparison error is traversed with a certain step.
First, implement stump classification,
Datamatrix. One row represents a training sample, and each column represents a feature.
Which feature does dimen indicate?
Threshval, Threshold Value
Threshineq: For demo-stump, only less than or greater than exists.
def stumpClassify(dataMatrix,dimen,threshVal,threshIneq): retArray = ones((shape(dataMatrix)[0],1)) if threshIneq == ‘lt‘: #lt,less than retArray[dataMatrix[:,dimen] <= threshVal] = -1.0 #boolean indexing else: retArray[dataMatrix[:,dimen] > threshVal] = -1.0 return retArray
Given the preceding parameter, we can determine that the classification of each sample is 1 or-1.
The following is an algorithm for solving the optimal stump classifier,
The parameter has a D vector, indicating the sample weight.
This is because we need to find the stump classifier with the smallest error in the weighted sample.
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 # INF, in python, it indicates an infinite for I in range (n): # traverse each feature rangemin = datamatrix [:, I]. min (); rangemax = datamatrix [:, I]. max (); # Calculate the value range of this feature stepsize = (rangemax-rangemin)/numsteps # Calculate the traversal step size for J in range (-1, INT (numsteps) + 1): # traverse this feature in step for inequal in ['lt ', 'gt']: # try to divide the direction, less than or greater than threshval = (rangemin + float (j) * stepsize) predictedvals = stumpclassify (datamatrix, I, threshval, inequal) # stump classification errarr = MAT (ones (M, 1 ))) # The initialization error is 1 errarr [predictedvals = labelmat] = 0 # calculation error. Set the deviation of the pair to 0 weightederror = D. T * errarr # Calculate the weighted error if weightederror <minerror: # if it is smaller than minerror, we can find a better stump classifier minerror = weightederror bestclasest = predictedvals. copy () beststump ['dim'] = I beststump ['thresh'] = threshval beststump ['ineq'] = inequal return bestump, minerror, bestclasest
Okay. Now we can provide the source code of the Adaboost algorithm,
Def inclusttrainds (dataarr, classlabels, numit = 40): weakclassarr = [] M = shape (dataarr) [0] # number of samples d = MAT (ones (M, 1 )) /m) # initialize the weight sample. The weights of all samples are equal to 1/M aggclassest = MAT (zeros (M, 1 ))) # cumulative classification result for I in range (numit): # Number of weak classifiers bestump, error, classest = buildstump (dataarr, classlabels, d) generated) # Calculate the optimal stump classifier print "D:", D. t alpha = float (0.5 * log (1.0-error)/MAX (error, 1e-16) #1. calculate the weight of this classifier. bestump ['alpha'] = Alph A weakclassarr. append (bestump) print "classest:", classest. t expon = multiply (-1 * Alpha * MAT (classlabels ). t, classest) d = multiply (D, exp (expon) #2. update sample weight d = D/d. sum () aggclassest + = Alpha * classest #3. update the cumulative classification result print "aggclassest:", aggclassest. t aggerrors = multiply (sign (aggclassest )! = # Calculate the cumulative classification error MAT (classlabels ). t, ones (M, 1) errorrate = aggerrors. sum ()/m print "total error:", errorrate, "\ n" If errorrate = 0.0: break #4. the error is 0, and the return weakclassarr
Where,
1. The formula for calculating the classifier weight is,
Max (error, 1e-16) to prevent the error from being 0
2. The formula for updating the sample weight is,
That is, when the judgment is correct, the weight is reduced. When the judgment is incorrect, the weight is increased.
Expon = multiply (-1 * Alpha * MAT (classlabels). T, classest)
-Alpha × classlabel × classest, that is, if the classification is correct, classlable = classest,-Alpha is still obtained; otherwise, Alpha is obtained.
3. aggclassest
Because we finally use the comprehensive results of multiple weak classifiers for classification.
Therefore, every time a weak classifier is generated, we add the classification result to aggclassest. aggclassest + = Alpha * classest
Aggerrors = multiply (sign (aggclassest )! = MAT (classlabels). T, ones (M, 1 )))
Because aggclassest is of the float type, use sign to convert to 1 ,-
Then! = MAT (classlabels). T, will generate a Boolean Vector
TIPS: here is why we need to multiply a vector of all 1, because we need to convert the boolean type to the int type.
You can try it in Python,
>>> (1 = 1) * 1
1
4. When the overall error of all weak classifiers is 0, no further iteration is required.
Next let's take a look at how to use the Adaboost algorithm for classification.
def adaClassify(datToClass,classifierArr): dataMatrix = mat(datToClass) m = shape(dataMatrix)[0] aggClassEst = mat(zeros((m,1))) for i in range(len(classifierArr)): classEst = stumpClassify(dataMatrix,classifierArr[i][‘dim‘], classifierArr[i][‘thresh‘], classifierArr[i][‘ineq‘]) aggClassEst += classifierArr[i][‘alpha‘]*classEst print aggClassEst return sign(aggClassEst)
Machine Learning in action -- AdaBoost