1. 程式人生 > >[機器學習]感知機(Perceptron)算法的MATLAB實現

[機器學習]感知機(Perceptron)算法的MATLAB實現

支持 ima 算法 not bsp iteration ptr 判斷 分類

感知機是一種二類分類的線性分類模型,屬於判別類型,它是神經網絡和支持向量機的基礎。

感知機的算法如圖所示:

技術分享

根據以上的算法,使用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實現