点击打开链接一、matlab代码
%读取模式样本数据
[X1,X2,X3,X4]=textread('data.data','%f%f%f%f','delimiter',',');
attrib=[X1,X2,X3,X4];
class1=zeros(10,3);%增广矩阵
class2=zeros(10,3);
for i=1:10
class1(i,:)=[attrib(i,1),attrib(i,2),1];
class2(i,:)=[-attrib(i,3),-attrib(i,4),-1];
end
t=0;%迭代次数
w=[0,0,0];%权向量初始值
c=0.1;%校正增量系数
wx=zeros(20,1);
%开始迭代
while(1)
for i=1:10
wx(i,1)=w*class1(i,:)';
if (wx(i,1)<=0)
w=w+c*class1(i,:);
end
end
for i=1:10
wx(i+10,1)=w*class2(i,:)';
if (wx(i+10,1)<=0)
w=w+c*class2(i,:);
end
end
t=t+1;
if (wx>0)
break;%分类结果全部正确,迭代终止
end
end
x=-8:8;
plot(class1(:,1),class1(:,2),['g','+']);hold on;
plot(-class2(:,1),-class2(:,2),['r','.']);hold on;
plot(x,-w(1,1)/w(1,2)*x-w(1,3)/w(1,2),'b');hold on;%绘制分类
%判断A,B属于哪个类别
A=[2,8,1];
B=[-0.6,7,1];
if (w*A'>0)
plot(A(1,1),A(1,2),['g','o']);hold on;
else
plot(A(1,1),A(1,2),['r','o']);hold on;
end
if (w*B'>0)
plot(B(1,1),B(1,2),['g','o']);hold on;
else
plot(B(1,1),B(1,2),['r','o']);hold on;
end
二、附测试数据
0.1,1.1,-3.0,-1.0
6.8,7.1,0.5,8.7
-3.5,-4.1,2.9,6.0
2.0,2.7,-0.1,5.2
4.1,2.8,-4.0,2.2
3.1,5.0,-1.3,3.7
-0.8,-1.3,-3.4,6.2
0.9,1.2,-4.1,3.4
5.0,6.4,-5.1,1.6
3.9,4.0,1.9,5.1
三、运行结果