本次实验用到的数据集是3个,分别为data.txt、data2.txt 和 data3.txt.数据集data.txt里面的数据是书本例2.1 的数据,其他两个是从网上找来用作测试代码用的。
1、数据集
data.txt 数据
data2.txt 数据
data3.txt 数据
2、具体实现代码
%perceptron_algrithm_original
clc,clear
%load the data 导入数据
data = load('data3.txt');
% data = load('data.txt');
% data = load('data2.txt');
x = [data(:,1),data(:,2)];
y = data(:,3);
len = length(y);
%plot the data point based on the label
for i = 1:len
if y(i) == 1
plot(x(i,1),x(i,2),'o');
hold on
end
if y(i) == -1
plot(x(i,1),x(i,2),'x');
hold on
end
end
%innitialize the parameters
w = [0,0];
b = 0;
r = 0.5;% learning rate
t = 0; %record the number of interations
for j = 1:len
while (y(j)*(dot(w,x(j,:))+b)) <= 0
w(1) = w(1) + r*y(j)*x(j,1);
w(2) = w(2) + r*y(j)*x(j,2);
w=[w(1),w(2)];
b = b + r*y(j);
t = t + 1;
for i = j:len
while (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);
w=[w(1),w(2)];
b = b + r*y(i);
t = t + 1;
end
end
end
end
%画出分类平面
%数据集:data、data2
%xt=-2:0.1:10;
xt=1.6:0.1:2.1; %画出分类平面
yt=(-w(1)*xt-b)/w(2);
plot(xt,yt);
3、运行结果显示
data.txt 结果
data2.txt 结果
data3.txt 结果