1. 程式人生 > >matlab 實現感知機線性二分類算法(Perceptron)

matlab 實現感知機線性二分類算法(Perceptron)

簡單的 learning 取值 fun end 隨機 -1 二維 技術分享

感知機是簡單的線性分類模型 ,是二分類模型。其間用到隨機梯度下降方法進行權值更新。參考他人代碼,用matlab實現總結下。

權值求解過程通過Perceptron.m函數完成

function W = Perceptron(X,y,learnRate,maxStep)

% Perceptron.m % Perception Learning Algorithm(感知機) % X一行為一個樣本,y的取值{-1,+1} % learnRate:學習率 % maxStep:最大叠代次數 [n,m] = size(X); X = [X ones(n,1)]; W=zeros(m+1,1); for step = 1:maxStep flag = true; for index = 1:n if sign(X(index,:) * W) ~= y(index) flag = false; W = W + learnRate * y(index) .* X(index,:)‘; end end if flag == true break; end end

之後測試一下,總共8個二維點(為了畫圖觀察選擇2維數據),代碼如下:

%%% test
close;
clear;
clc;

X = [0,0;1,0;2,0;1,1;0,2;1,3;2,4;4,2];
y = [-1,-1,-1,-1,-1,1,1,1];

n = size(y,2);
for i = 1:n
    if y(i) == 1
        plot(X(i,1),X(i,2),‘rs‘);
    end
    if y(i) == -1
        plot(X(i,1),X(i,2),‘b*‘);
    end
    hold on;
end

W = Perceptron(X,y,1,500);

xline = linspace(0,5,50);
yline = -W(1)/W(2) * xline - W(3)/W(2); % w1*x1+w2*x2+w3=0,x2看成yline
plot(xline,yline);

其顯示圖為:

技術分享

(完)

matlab 實現感知機線性二分類算法(Perceptron)