AdaBoost—MATLAB代码

 在网上看了几篇AdaBoost的介绍后,感觉网上介绍的都不好,不能够让人完全理解,因此就下载了一个外国人写的代码,总算透彻的理解了AdaBoost,可以向Transfer开进了,现在分享一下代码:

     主函数代码

[plain]  view plain  copy
  1. clear;clc;  
  2. %  
  3. % DEMONSTRATION OF ADABOOST_tr and ADABOOST_te  
  4. %  
  5. % Just type "demo" to run the demo.  
  6. %  
  7. % Using adaboost with linear threshold classifier  
  8. % for a two class classification problem.  
  9. %  
  10. % Bug Reporting: Please contact the author for bug reporting and comments.  
  11. %  
  12. % Cuneyt Mertayak  
  13. % email: cuneyt.mertayak@gmail.com  
  14. % version: 1.0  
  15. % date: 21/05/2007  
  16. % Creating the training and testing sets  
  17. %  
  18. tr_n = 200;  
  19. te_n = 200;  
  20. weak_learner_n = 20;  
  21.   
  22. tr_set = abs(rand(tr_n,2))*100;  
  23. te_set = abs(rand(te_n,2))*100;  
  24.   
  25. tr_labels = (tr_set(:,1)-tr_set(:,2) > 0) + 1;  
  26. te_labels = (te_set(:,1)-te_set(:,2) > 0) + 1;  
  27.   
  28. % Displaying the training and testing sets  
  29. figure;  
  30. subplot(2,2,1);  
  31. hold on; axis square;  
  32. indices = tr_labels==1;  
  33. plot(tr_set(indices,1),tr_set(indices,2),'b*');  
  34. indices = ~indices;  
  35. plot(tr_set(indices,1),tr_set(indices,2),'r*');  
  36. title('Training set');  
  37.   
  38. subplot(2,2,2);  
  39. hold on; axis square;  
  40. indices = te_labels==1;  
  41. plot(te_set(indices,1),te_set(indices,2),'b*');  
  42. indices = ~indices;  
  43. plot(te_set(indices,1),te_set(indices,2),'r*');  
  44. title('Testing set');  
  45.   
  46. % Training and testing error rates  
  47. tr_error = zeros(1,weak_learner_n);  
  48. te_error = zeros(1,weak_learner_n);  
  49.   
  50. for i=1:weak_learner_n  
  51.     adaboost_model = ADABOOST_tr(@threshold_tr,@threshold_te,tr_set,tr_labels,i);  
  52.     % 训练样本测试  
  53.     [L_tr,hits_tr] = ADABOOST_te(adaboost_model,@threshold_te,tr_set,tr_labels);  
  54.     tr_error(i) = (tr_n-hits_tr)/tr_n;  
  55.     % 测试样本测试  
  56.     [L_te,hits_te] = ADABOOST_te(adaboost_model,@threshold_te,te_set,te_labels);  
  57.     te_error(i) = (te_n-hits_te)/te_n;  
  58. end  
  59.   
  60. subplot(2,2,3);  
  61. plot(1:weak_learner_n,tr_error);  
  62. axis([1,weak_learner_n,0,1]);  
  63. title('Training Error');  
  64. xlabel('weak classifier number');  
  65. ylabel('error rate');  
  66. grid on;  
  67.   
  68. subplot(2,2,4); axis square;  
  69. plot(1:weak_learner_n,te_error);  
  70. axis([1,weak_learner_n,0,1]);  
  71. title('Testing Error');  
  72. xlabel('weak classifier number');  
  73. ylabel('error rate');  
  74. grid on;  

      为了计算每一种迭代次数的准确率的时候,迭代次数增加的时候让计算机重复计算


调用的分类器训练函数代码:

[plain]  view plain  copy
  1. function model = threshold_tr(train_set, sample_weights, labels)  
  2. %  
  3. % TRAINING THRESHOLD CLASSIFIER  
  4. %  
  5. %  Training of the basic linear classifier where seperation hyperplane  
  6. %  is perpedicular to one dimension.  
  7. %  
  8. %  model = threshold_tr(train_set, sample_weights, labels)  
  9. %   train_set: an NxD-matrix, each row is a training sample in the D dimensional feature  
  10. %            space.  
  11. %        sample_weights: an Nx1-vector, each entry is the weight of the corresponding training sample  
  12. %        labels: Nx1 dimensional vector, each entry is the corresponding label (either 1 or 2)  
  13. %  
  14. %        model: the ouput model. It consists of  
  15. %            1) min_error: training error  
  16. %            2) min_error_thr: threshold value  
  17. %            3) pos_neg: whether up-direction shows the positive region (label:2, 'pos') or  
  18. %                the negative region (label:1, 'neg')  
  19. %  
  20. % Bug Reporting: Please contact the author for bug reporting and comments.  
  21. %  
  22. % Cuneyt Mertayak  
  23. % email: cuneyt.mertayak@gmail.com  
  24. % version: 1.0  
  25. % date: 21/05/2007  
  26.   
  27. model = struct('min_error',[],'min_error_thr',[],'pos_neg',[],'dim',[]);  
  28.   
  29. sample_n = size(train_set,1);  
  30. min_error = sum(sample_weights);  
  31. min_error_thr = 0;  
  32. pos_neg = 'pos';  
  33.   
  34. % for each dimension  
  35. for dim=1:size(train_set,2)  
  36.     sorted = sort(train_set(:,dim),1,'ascend');  
  37.       
  38.     % for each interval in the specified dimension  
  39.     for i=1:(sample_n+1)  
  40.         if(i==1)  
  41.             thr = sorted(1)-0.5;  
  42.         elseif(i==sample_n+1)  
  43.             thr = sorted(sample_n)+0.5;  
  44.         else  
  45.             thr = (sorted(i-1)+sorted(i))/2;  
  46.         end  
  47.           
  48.         ind1 = train_set(:,dim) < thr;  
  49.         ind2 = ~ind1;  
  50.         tmp_err  =  sum(sample_weights((labels.*ind1)==2))+sum(sample_weights((labels.*ind2)==1));  
  51.           
  52.         if(tmp_err < min_error)  
  53.             min_error = tmp_err;  
  54.             min_error_thr = thr;  
  55.             pos_neg = 'pos';  
  56.             model.dim = dim;  
  57.         end  
  58.           
  59.         ind1 = train_set(:,dim) < thr;  
  60.         ind2 = ~ind1;  
  61.         tmp_err  =  sum(sample_weights((labels.*ind1)==1))+sum(sample_weights((labels.*ind2)==2));  
  62.           
  63.         if(tmp_err < min_error)  
  64.             min_error = tmp_err;  
  65.             min_error_thr = thr;  
  66.             pos_neg = 'neg';  
  67.             model.dim = dim;  
  68.         end  
  69.     end  
  70. end  
  71.   
  72. model.min_error = min_error;  
  73. model.min_error_thr = min_error_thr;  
  74. model.pos_neg = pos_neg;  

     分类器的输入输出就不说了,分类器是最简单的与坐标轴垂直的超平面,模型从所有的dim*(sample_n+1)个超平面中,选择加权分类错误率最小的超平面,作为当前权重的最优超平面,并输出结果


调用的分类器测试函数:

[plain]  view plain  copy
  1. function [L,hits,error_rate] = threshold_te(model,test_set,sample_weights,true_labels)  
  2. %  
  3. % TESTING THRESHOLD CLASSIFIER  
  4. %  
  5. %    Testing of the basic linear classifier where seperation hyperplane is  
  6. %  perpedicular to one dimension.  
  7. %  
  8. %  [L,hits,error_rate] = threshold_te(model,test_set,sample_weights,true_labels)  
  9. %  
  10. %   model: the model that is outputed from threshold_tr. It consists of  
  11. %    1) min_error: training error  
  12. %    2) min_error_thr: threshold value  
  13. %    3) pos_neg: whether up-direction shows the positive region (label:2, 'pos') or  
  14. %     the negative region (label:1, 'neg')  
  15. %   test_set: an NxD-matrix, each row is a testing sample in the D dimensional feature  
  16. %    space.  
  17. %   sample_weights:  an  Nx1-vector,  each  entry  is  the  weight  of  the  corresponding  test sample  
  18. %   true_labels: Nx1 dimensional vector, each entry is the corresponding label (either 1 or 2)  
  19. %  
  20. %   L: an Nx2-matrix showing likelihoods of each class  
  21. %   hits: the number of hits  
  22. %   error_rate: the error rate with the sample weights  
  23. %  
  24. %  
  25. % Bug Reporting: Please contact the author for bug reporting and comments.  
  26. %  
  27. % Cuneyt Mertayak  
  28. % email: cuneyt.mertayak@gmail.com  
  29. % version: 1.0  
  30. % date: 21/05/2007  
  31.   
  32. feat = test_set(:,model.dim);  
  33. if(strcmp(model.pos_neg,'pos'))  
  34.     ind = (feat>model.min_error_thr)+1;  
  35. else  
  36.     ind = (feat<model.min_error_thr)+1;  
  37. end  
  38.   
  39. hits = sum(ind==true_labels);  
  40. error_rate = sum(sample_weights(ind~=true_labels));  
  41.   
  42. L = zeros(length(feat),2);  
  43. L(ind==1,1) = 1;  
  44. L(ind==2,2) = 1;  

      模型训练函数就是从当前模型训练输入的数据,得到错误率等指标,这个跟模型训练函数对应,看懂那个这里就很简单,从训练的模型中,找出模型需要的那一纬数据,分类,不说了。


调用的AdaBoost训练函数:

[plain]  view plain  copy
  1. function  adaboost_model  =  ADABOOST_tr(tr_func_handle,te_func_handle,train_set,labels,no_of_hypothesis)  
  2. %  
  3. % ADABOOST TRAINING: A META-LEARNING ALGORITHM  
  4. %   adaboost_model = ADABOOST_tr(tr_func_handle,te_func_handle,  
  5. %                                train_set,labels,no_of_hypothesis)  
  6. %  
  7. %         'tr_func_handle' and 'te_func_handle' are function handles for  
  8. %         training and testing of a weak learner, respectively. The weak learner  
  9. %         has to support the learning in weighted datasets. The prototypes  
  10. %         of these functions has to be as follows.  
  11. %  
  12. %         model = train_func(train_set,sample_weights,labels)  
  13. %                     train_set: a TxD-matrix where each row is a training sample in  
  14. %                         a D dimensional feature space.  
  15. %                     sample_weights: a Tx1 dimensional vector, the i-th entry  
  16. %                         of which denotes the weight of the i-th sample.  
  17. %                     labels: a Tx1 dimensional vector, the i-th entry of which  
  18. %                         is the label of the i-th sample.  
  19. %                     model: the output model of the training phase, which can  
  20. %                         consists of parameters estimated.  
  21. %  
  22. %         [L,hits,error_rate] = test_func(model,test_set,sample_weights,true_labels)  
  23. %                     model: the output of train_func  
  24. %                     test_set: a KxD dimensional matrix, each of whose row is a  
  25. %                         testing sample in a D dimensional feature space.  
  26. %                     sample_weights:   a Dx1 dimensional vector, the i-th entry  
  27. %                         of which denotes the weight of the i-th sample.  
  28.   
  29. %                     true_labels: a Dx1 dimensional vector, the i-th entry of which  
  30. %                         is the label of the i-th sample.  
  31. %                     L: a Dx1-array with the predicted labels of the samples.  
  32. %                     hits: number of hits, calculated with the comparison of L and  
  33. %                         true_labels.  
  34. %                     error_rate: number of misses divided by the number of samples.  
  35. %  
  36. %  
  37. %         'train_set' contains the samples for training and it is NxD matrix  
  38. %         where N is the number of samples and D is the dimension of the  
  39. %         feature space. 'labels' is an Nx1 matrix containing the class  
  40. %         labels of the samples. 'no_of_hypothesis' is the number of weak  
  41. %         learners to be used.  
  42. %  
  43. %         The output 'adaboost_model' is a structure with the fields  
  44. %          - 'weights': 1x'no_of_hypothesis' matrix specifying the weights  
  45. %                       of the resulted weighted majority voting combination  
  46. %          - 'parameters': 1x'no_of_hypothesis' structure matrix specifying  
  47. %                          the special parameters of the hypothesis that is  
  48. %                          created at the corresponding iteration of  
  49. %                          learning algorithm  
  50. %  
  51. %         Specific Properties That Must Be Satisfied by The Function pointed  
  52. %         by 'func_handle'  
  53. %         ------------------------------------------------------------------  
  54. %  
  55. % Note: Labels must be positive integers from 1 upto the number of classes.  
  56. % Node-2: Weighting is done as specified in AIMA book, Stuart Russell et.al. (sec edition)  
  57. %  
  58. % Bug Reporting: Please contact the author for bug reporting and comments.  
  59. %  
  60. % Cuneyt Mertayak  
  61. % email: cuneyt.mertayak@gmail.com  
  62. % version: 1.0  
  63. % date: 21/05/2007  
  64. %  
  65.   
  66. adaboost_model = struct('weights',zeros(1,no_of_hypothesis),'parameters',[]); %cell(1,no_of_hypothesis));  
  67.   
  68. sample_n = size(train_set,1);  
  69. samples_weight = ones(sample_n,1)/sample_n;  
  70.   
  71. for turn=1:no_of_hypothesis  
  72.     model=tr_func_handle(train_set,samples_weight,labels);  
  73.     adaboost_model.parameters{turn} =model;  
  74.     [L,hits,error_rate]=te_func_handle(adaboost_model.parameters{turn},train_set,samples_weight,labels);  
  75.     if(error_rate==1)  
  76.         error_rate=1-eps;  
  77.     elseif(error_rate==0)  
  78.         error_rate=eps;  
  79.     end  
  80.       
  81.     % The weight of the turn-th weak classifier  
  82.     adaboost_model.weights(turn) = log10((1-error_rate)/error_rate);  
  83.     C=likelihood2class(L);  
  84.     t_labeled=(C==labels);  % true labeled samples  
  85.       
  86.     % Importance of the true classified samples is decreased for the next weak classifier  
  87.     samples_weight(t_labeled) = samples_weight(t_labeled)*((error_rate)/(1-error_rate));  
  88.       
  89.     % Normalization  
  90.     samples_weight = samples_weight/sum(samples_weight);  
  91. end  
  92.   
  93. % Normalization  
  94. adaboost_model.weights=adaboost_model.weights/sum(adaboost_model.weights);  

      根据输入的迭代次数,迭代,得到新模型,计算新模型权重,更新样本权重,迭代。。。。。。



调用的AdaBoost测试函数:

[plain]  view plain  copy
  1. function [L,hits] = ADABOOST_te(adaboost_model,te_func_handle,test_set,true_labels)  
  2. %  
  3. % ADABOOST TESTING  
  4. %  
  5. %   [L,hits] = ADABOOST_te(adaboost_model,te_func_handle,train_set,  
  6. %                          true_labels)  
  7. %  
  8. %            'te_func_handle' is a handle to the testing function of a  
  9. %            learning (weak) algorithm whose prototype is shown below.  
  10. %  
  11. %            [L,hits,error_rate] = test_func(model,test_set,sample_weights,true_labels)  
  12. %                     model: the output of train_func  
  13. %                     test_set: a KxD dimensional matrix, each of whose row is a  
  14. %                         testing sample in a D dimensional feature space.  
  15. %                     sample_weights:   a Dx1 dimensional vector, the i-th entry  
  16. %                         of which denotes the weight of the i-th sample.  
  17. %                     true_labels: a Dx1 dimensional vector, the i-th entry of which  
  18.   
  19. %                         is the label of the i-th sample.  
  20. %                     L: a Dx1-array with the predicted labels of the samples.  
  21. %                     hits: number of hits, calculated with the comparison of L and  
  22. %                         true_labels.  
  23. %                     error_rate: number of misses divided by the number of samples.  
  24. %  
  25. %            It is the corresponding testing  
  26. %            module of the function that is specified in the training phase.  
  27. %            'test_set' is a NxD matrix where N is the number of samples  
  28. %            in the test set and D is the dimension of the feature space.  
  29. %            'true_labels' is a Nx1 matrix specifying the class label of  
  30. %            each corresponding sample's features (each row) in 'test_set'.  
  31. %            'adaboost_model' is the model that is generated by the function  
  32. %            'ADABOOST_tr'.  
  33. %  
  34. %            'L' is the likelihoods that are assigned by the 'ADABOOST_te'.  
  35. %            'hits' is the number of correctly predicted labels.  
  36. %  
  37. %         Specific Properties That Must Be Satisfied by The Function pointed  
  38. %         by 'func_handle'  
  39. %         ------------------------------------------------------------------  
  40. %  
  41. % Notice: Labels must be positive integer values from 1 upto the number classes.  
  42. %  
  43. % Bug Reporting: Please contact the author for bug reporting and comments.  
  44. %  
  45. % Cuneyt Mertayak  
  46. % email: cuneyt.mertayak@gmail.com  
  47. % version: 1.0  
  48. % date: 21/05/2007  
  49. %  
  50.   
  51. hypothesis_n = length(adaboost_model.weights);  
  52. sample_n = size(test_set,1);  
  53. class_n = length(unique(true_labels));  
  54. temp_L = zeros(sample_n,class_n,hypothesis_n);   % likelihoods for each weak classifier  
  55.   
  56. % for each weak classifier, likelihoods of test samples are collected  
  57. for i=1:hypothesis_n  
  58.     [temp_L(:,:,i),hits,error_rate] = te_func_handle(adaboost_model.parameters{i},test_set,ones(sample_n,1),true_labels);  
  59.     temp_L(:,:,i) = temp_L(:,:,i)*adaboost_model.weights(i);  
  60. end  
  61. L = sum(temp_L,3);  
  62. hits = sum(likelihood2class(L)==true_labels);  

      懒得说了,把训练的模型,计算每个模型的结果,加权,投票决定最终结果。


      一个结果辅助转换函数:

[plain]  view plain  copy
  1. function classes = likelihood2class(likelihoods)   
  2. %   
  3. % LIKELIHOODS TO CLASSES   
  4. %   
  5. % classes = likelihood2class(likelihoods)   
  6. %   
  7. %   Find the class assignment of the samples from the likelihoods   
  8. %   'likelihoods' an NxD matrix where N is the number of samples and   
  9. %   D is the dimension of the feature space. 'likelihoods(i,j)' is   
  10. %   the i-th samples likelihood of belonging to class-j.   
  11. %   
  12. %   'classes' contains the class index of the each sample maximum likelihood   
  13. %   
  14. % Bug Reporting: Please contact the author for bug reporting and comments.   
  15. %   
  16. % Cuneyt Mertayak   
  17. % email: cuneyt.mertayak@gmail.com   
  18. % version: 1.0   
  19. % date: 21/05/2007   
  20. %   
  21.    
  22. [sample_n,class_n] = size(likelihoods);   
  23. maxs = (likelihoods==repmat(max(likelihoods,[],2),[1,class_n]));   
  24.    
  25. classes=zeros(sample_n,1);   
  26. for i=1:sample_n   
  27.   classes(i) = find(maxs(i,:),1);   
  28. end  

      这个也不说了,就是把结果转化成矩阵,这个作用是什么,我也懒得看了,看别人的代码,不用看这么细,没必要。抓住精髓就好了。休息。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值