matlab编程
clear all
%生成点
n=100;
x1=2*rand(1)-1;y1=2*rand(1)-1;
x2=2*rand(1)-1;y2=2*rand(1)-1;
ps=2*rand(n,2)-1;
%要去y1<y2
if y1>y2
a=x1;x1=x2;x2=a;
a=y1;y1=y2;y2=a;
end
%训练输出
realout=zeros(n,1);
for i=1:n
realout(i)=pinline(x1,y1,x2,y2,ps(i,1),ps(i,2));
end
w1=0;w2=0;w0=0;
%随机找个点
pick=ceil(n*rand(1));
%调整权重
w1=w1+pinline(x1,y1,x2,y2,ps(pick,1),ps(pick,2))*ps(pick,1);
w2=w2+pinline(x1,y1,x2,y2,ps(pick,1),ps(pick,2))*ps(pick,2);
w0=w0+pinline(x1,y1,x2,y2,ps(pick,1),ps(pick,2))*1;
count=0;
index=1;
while(index)
count=count+1;
%x3=(-w0)/w1;y3=0; %特殊情况是w1=0,方程是y=c
%x4=(-w0-w2)/w1; y4=1;
testout=zeros(n,1);
for m=1:1:n
testout(m)=sign(w0+w1*ps(m,1)+w2*ps(m,2));
end
%是否可以了呢
diff=realout-testout;
if(sum(abs(diff))~=0)
diff(diff~=0)=1;
total=ceil(rand(1)*sum(diff));
count2=0;
for i=1:n
if(diff(i)==0)
else
count2=count2+1;
end
if(count2==total)
break;
end
end
%不可以的处理
w1=w1+pinline(x1,y1,x2,y2,ps(i,1),ps(i,2))*ps(i,1);
w2=w2+pinline(x1,y1,x2,y2,ps(i,1),ps(i,2))*ps(i,2);
w0=w0+pinline(x1,y1,x2,y2,ps(i,1),ps(i,2))*1;
else
index=0;
%sprintf('hehe')
%break;
end
end
scatter(ps(:,1),ps(:,1),'k')
scatter(ps(:,1),ps(:,2),'k')
xx1=-1:0.01:1;
yy1=(y2-y1)/(x2-x1)*(xx1-x1)+y1;
hold on
plot(xx1,yy1,'r')
%yy2=(y4-y3)/(x4-x3)*(xx1-x3)+y3;
yy2=(-w1/w2)*xx1-w0/w2;
hold on
plot(xx1,yy2,'b')
-
比较好看的一个结果
网友评论