下面是实验结果:
main.m
<span style="font-family:Times New Roman;font-size:14px;">data=[0 0 0;0 1 1;1 0 1;1 1 2;2 1 1;1 2 3;2 2 4;3 2 1]; data1=[6 6 7;6 7 2;7 6 6;7 7 8;7 8 9;8 6 7;8 7 6;8 8 8;8 9 5;9 7 7;9 8 9;9 9 5]; plot3(data(:,1),data(:,2),data(:,3),'ko','LineWidth', 3); hold on plot3(data1(:,1),data1(:,2),data1(:,3),'r+','LineWidth', 3); hold on grid on data=[data;data1]; data=data'; t=[1 1 1 1 1 1 1 1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1]; [w mis_class]=perceptron(data,t); a1=-w(1)/w(4); a2=-w(2)/w(4); a3=-w(3)/w(4); x1=0:0.1:10; x2=0:0.1:10; [X,Y]=meshgrid(x1,x2); y=a1+a2*X+a3*Y; mesh(X,Y,y);</span>
perceptron.m
<span style="font-family:Times New Roman;font-size:14px;">function [w, mis_class] = perceptron(X,t) % The perceptron algorithm %by LiFeiteng email:[email protected] % X : D*N维输入数据 % t : {+1,-1}标签 % % w : [w0 w1 w2] % mis_class : 错误分类数据点数 % 对t做简单的检查 if size(unique(t),2)~=2 return elseif max(t)~=1 return elseif min(t)~=-1 return end [dim num_data] = size(X); w = ones(dim+1,1);%%w = [w0 w1 w2]' X = [ones(1,num_data); X]; maxiter = 1000; mis_class = 0; iter = 0; while iter<maxiter iter = iter+1; y = w'*X; label = ones(1, num_data);%{+1,-1} label(y<=0) = -1; index = find(label~=t); %错误分类的点 mis_class = numel(index); %错误分类点的数目 if mis_class==0 break end for i = 1:mis_class w = w + X(:,index(i))*t(index(i)); end end if iter==maxiter disp(['达到最大迭代次数' num2str(maxiter)]) end </span>
时间: 2024-10-08 21:29:30