Fisher线性判别与感知器算法Matlab实现

来源:互联网 发布:太平洋电脑软件下载 编辑:程序博客网 时间:2024/05/01 03:17

参考用书:


本文是在学习此书Chapter4时,跑的实验。

4.1.4 Fisher‘s Linear Discriminate


[plain] view plaincopy
  1. function [w y1 y2 Jw] = FisherLinearDiscriminat(data, label)  
  2. % FLD Fisher Linear Discriminant.  
  3. % data : D*N data  
  4. % label : {+1,-1}  
  5. % Reference:M.Bishop Pattern Recognition and Machine Learning p186-p189  
  6.   
  7. % compute means and scatter matrix  
  8. %-------------------------------  
  9. inx1 = find( label == 1);  
  10. inx2 = find( label == -1);  
  11. n1 = length(inx1);  
  12. n2 = length(inx2);  
  13.   
  14. m1 = mean(data(:,inx1),2);  
  15. m2 = mean(data(:,inx2),2);  
  16.   
  17. S1 = (data(:,inx1)-m1*ones(1,n1))*(data(:,inx1)-m1*ones(1,n1))';  
  18. S2 = (data(:,inx2)-m2*ones(1,n2))*(data(:,inx2)-m2*ones(1,n2))';  
  19. Sw = S1 + S2;  
  20.   
  21. % compute FLD   
  22. %-------------------------------  
  23. W = inv(Sw)*(m1-m2);  
  24.   
  25. y1 = W'*m1;  %label=+1  
  26. y2 = W'*m2;  %label=-1  
  27. w = W;  
  28. Jw = (y1-y2)^2/(W'*Sw*W);  


4.1.7 The perceptron algorithm 

[plain] view plaincopy
  1. function [w, mis_class] = perceptron(X,t)  
  2. % The perceptron algorithm   
  3. %by LiFeiteng   email:lifeiteng0422@gmail.com  
  4. %   X : D*N维输入数据  
  5. %   t : {+1,-1}标签  
  6. %     
  7. %   w : [w0 w1 w2]     
  8. %   mis_class : 错误分类数据点数  
  9.   
  10. %  对t做简单的检查  
  11. if size(unique(t),2)~=2  
  12.     return  
  13. elseif max(t)~=1  
  14.     return  
  15. elseif min(t)~=-1  
  16.     return  
  17. end  
  18.   
  19. [dim num_data] = size(X);  
  20. w = ones(dim+1,1);%%w = [w0 w1 w2]'  
  21. X = [ones(1,num_data); X];  
  22. maxiter = 100000;  
  23. mis_class = 0;  
  24. iter = 0;  
  25.   
  26. while iter<maxiter  
  27.     iter = iter+1;  
  28.     y = w'*X;  
  29.     label = ones(1, num_data);%{+1,-1}  
  30.     label(y<=0) = -1;    
  31.     index = find(label~=t); %错误分类的点  
  32.     mis_class = numel(index); %错误分类点的数目     
  33.     if mis_class==0  
  34.         break  
  35.     end  
  36.     for i = 1:mis_class  
  37.         w = w + X(:,index(i))*t(index(i));  
  38.     end  
  39. end  
  40. if iter==maxiter  
  41.     disp(['达到最大迭代次数' num2str(maxiter)])  
  42. end  


0 0
原创粉丝点击