感知器算法----Matlab实现

data=[0 0 -1;0 1 1 ; -1 0 1 ; 1 1 -1];
X = data(:, [1, 2]); y = data(:, 3);
m = size(X,1); 
plotData2(X,y);
X = [ones(m,1) X];

error = 1;
W=[0;0;0];
first = 1;
tim=0;
alph=0.1;

hold on
axis([-2 2 -2 2]);
x1=-2:0.2:2;

while error>0
  error=0; 
  for i = 1:m
     if ( ((W'*(X(i,:)'))*y(i) <= 0 )|| (first == 1) )
         first=0;
         error=error+1;
         tim=tim+1;
         W = W + alph*(X(i,:))'*y(i);
         fprintf('%d\n',tim);
         if W(3)~=0 && W(2)~=0
            y1=-(W(1)/W(3)+W(2)*x1/W(3));
            plot(x1,y1,'-b');  
        end;
      end;  
   end;
 end;
 
if W(3)~=0 && W(2)~=0
    y1=-(W(1)/W(3)+W(2)*x1/W(3));
    plot(x1,y1,'r');  
end;

 
hold off
 
function plotData2(X, y)
figure; hold on;

pos = find(y==1) ;
neg = find(y==-1);

fprintf('%d\n\n',pos);

fprintf('%d\n',neg);

% Plot Examples
plot(X(pos, 1), X(pos, 2), 'k+','LineWidth', 2, ...
     'MarkerSize', 9);
plot(X(neg, 1), X(neg, 2), 'ko', 'MarkerFaceColor', 'r', ...
     'MarkerSize', 7);

hold off;

end

效果是这样的:

感知器算法----Matlab实现_第1张图片

权值为:

-0.100000000000000
-0.300000000000000
0.200000000000000





你可能感兴趣的:(机器学习)