码迷,mamicode.com
首页 > 编程语言 > 详细

[机器学习]感知机(Perceptron)算法的MATLAB实现

时间:2017-08-16 00:03:51      阅读:305      评论:0      收藏:0      [点我收藏+]

标签:向量   record   code   程序   初始化   技术分享   data   结果   hang   

感知机是一种二类分类的线性分类模型,属于判别类型,它是神经网络和支持向量机的基础。

感知机的算法如图所示:

技术分享

根据以上的算法,使用MATLAB对一组标签为“1”和“-1”的数据进行训练,得到的分类超平面。

数据为:

技术分享

 

%%perceptron
clc
clear

%load the data  导入数据
data=load(testSet.txt);
%Sometimes you do not need too precise data
% data=roundn(data,-1); 

x=[data(:,1),data(:,2)];
y=data(:,3);
k=length(y);

%plot the data point based on the label  根据数据的标签画出散点图
for j=1:k
    if y(j)==1
     plot(x(j,1),x(j,2),o);
%      L={num2str(j)};
%      text (x(j,1),x(j,2),L);
     hold on
    end
    if y(j)==-1
     plot(x(j,1),x(j,2),x);
%      L={num2str(j)},
%      text (x(j,1),x(j,2),L);
     hold on
    end 
end     

%initialize the parameters  初始化参数,对应算法第一步
w=[0,0];
b=0;
r=0.5;  %learningrate

con=0;  %set the condition
t=0;    %record the number of iterations
br=[];  %record the change of b
wr=[];  %record the change of w


while con==0                           %条件为训练集没有误分类点
   for i=1:k
     if (y(i)*(dot(w,x(i,:))+b))<=0    %判断是否分类错误
      w(1)=w(1)+r*y(i)*x(i,1);         %对应算法第三步
      w(2)=w(2)+r*y(i)*x(i,2);
      b=b+r*y(i);
      w=[w(1),w(2)];
      wr=[wr;w];
      br=[br,b];
      t=t+1;
     end
   end 

   for i=1:k
      con1(i)=(y(i)*(dot(w,x(i,:))+b));    %如果所有点都分类正确,则con1中所有元素都大于0
   end
   con=(all(con1(:)>0))
end

xt=-2:0.1:10;                              %画出分类平面
yt=(-w(1)*xt-b)/w(2);
plot(xt,yt);

运行上述程序,得到的结果如下所示:

技术分享

 

[机器学习]感知机(Perceptron)算法的MATLAB实现

标签:向量   record   code   程序   初始化   技术分享   data   结果   hang   

原文地址:http://www.cnblogs.com/youngsea/p/7368359.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!