matlab 实现感知机线性二分类算法(Perceptron)

感知机是简单的线性分类模型 ,是二分类模型。其间用到随机梯度下降方法进行权值更新。参考他人代码,用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);

其显示图为:

(完)

原文地址:https://www.cnblogs.com/mjk961/p/6964273.html