|
AdaBoost分类识别:
使用环境:Win7-32bit-matlab2014a-CPU
- function [ada_train, ada_test]= adaboost(Xtrain, Ytrain, Xtest)
- % AdaBoost function
- % (X_train-> input: training set)
- % (Y_train-> target)
- % (Xtest-> input: testing set)
- % (ada_train-> label: training set)
- % (ada_test-> label: testing set)
- % Choosen Weak classifiers:
- % 1. GDA
- % 2. knn (NumNeighbors = 30)
- N=size(Xtrain,1); % 训练样本个数
- a=[Xtrain Ytrain]; % 【训练样本输入+输出】
- % 初始化
- D=(1/N)*ones(N,1);
- Dt=[];
- h_=[];
- Classifiers=2; % GDA+KNN
- eps=zeros(Classifiers,1); % 每个弱分类器的误差
- for T=1:Classifiers
- p_min=min(D);
- p_max=max(D);
- k=1;
- for i=1:length(D)
- p = (p_max-p_min)*rand(1) + p_min; % 在[p_min,p_max]内随机产生
- if D(i)>=p % 权值大于p值
- d(k,:)=a(i,:);
- k=k+1;
- end
- t=randi(size(d,1));
- Dt=[Dt; d(t,:)];
- end
-
- X=Dt(:,1:end-1);
- Y=Dt(:,end);
-
- if T==1
- % gda
- gda_in=fitcdiscr(X, Y);
- gda_out=predict(gda_in, X);
- h=gda_out;
- Dt=[]; % 置空
- end
-
- if T==2
- % knn with (30 Nearest Neighbour)
- knn_in=fitcknn(X,Y,'NumNeighbors',30);
- knn_out=predict(knn_in, X);
- h = knn_out;
- Dt=[]; % 置空
- end
-
- h_=[h_ h]; % 存储不同弱分类器的结果
-
- % weighted error --- 不同分类器预测错误的样本权值和
- for i=1:length(Y)
- if (h_(i, T)~=Y(i))
- eps(T)=eps(T)+D(i,:);
- end
- end
-
- % Hypothesis weight --- 不同分类器的权值
- alpha(T)=0.5*log((1-eps(T))/eps(T));
-
- % Update weights --- 不同样本的权值
- D=D.*exp((-1).*Y.*alpha(T).*h);
- D=D./sum(D); % 归一化
-
- end
- % final vote
- H(:,1)=predict(gda_in, Xtrain);
- H(:,2)=predict(knn_in, Xtrain);
- ada_train(:,1)=sign(H*alpha');
- % for test set
- Htest(:,1)=predict(gda_in, Xtest);
- Htest(:,2)=predict(knn_in, Xtest);
- ada_test(:,1)=sign(Htest*alpha');
复制代码 主程序如下:- % Adaboost(GDA, KNN)
- Xtrain = X;
- Ytrain = Y;
- iter = 1;
- fm_=[];
- for iter = 1:50
- [~, ada_test(:,iter)] = adaboost(X, Y, Xtest);
- fm_ = [fm_; confusion_mat(Ytest, ada_test(:,iter))];
- end
- [fm, iter] = max(fm_);
- ada_out = ada_test(:,iter);
- [Fmeasure(3), Accuracy(3)] = confusion_mat(Ytest,ada_out);
- Fmeasure_Adaboost = Fmeasure(3)
- Accuracy_Adaboost = Accuracy(3)
复制代码 注:
(1)输入参数,例如:X是320x2的矩阵、Y是320x1的矩阵、Xtest是81x2的矩阵,Ytest是81x1的矩阵;
(2)混淆矩阵confusion_mat的计算方法参考:http://halcom.cn/forum.php?mod=v ... ge=1&extra=#pid3748
|
|