首页 > 代码库 > perceptron and ANN

perceptron and ANN

技术分享

技术分享

 1 %% Perceptron Regression
 2 close all
 3 clear
 4 
 5 %%load data
 6 x = load(ex4x.dat);
 7 y = load(ex4y.dat);
 8 
 9 x=ones(80,2);
10 for i=1:80
11     x(i,1)=mod(i,10);
12     x(i,2)=floor(i/10);
13 end
14 
15 for i=1:80
16     if (x(i,1)+x(i,2))<10
17         y(i)=0;
18     else
19         y(i)=1;
20     end
21 end
22 
23 [m, n] = size(x);
24 
25 % Add intercept term to x
26 x = [ones(m, 1), x];
27 
28 %%draw picture
29 % find returns the indices of the
30 % rows meeting the specified condition
31 pos = find(y == 1);
32 neg = find(y == 0);
33 % Assume the features are in the 2nd and 3rd
34 % columns of x
35 figure(NumberTitle, off, Name, 感知机);
36 plot(x(pos, 2), x(pos,3), +);
37 hold on;
38 plot(x(neg, 2), x(neg, 3), o);
39 
40 %进行初始化
41 s = 1;                     % 标识符,当s=0时,表示迭代终止
42 n = 0;                     % 表示迭代的次数
43 N = 10000;                 %定义N为最大分类判别次数,判别次数超过此值则认定样本无法分类。
44 w= [0,0,0];                % 取权向量初始值
45 
46 % 开始迭代
47 while s
48     J = 0;                % 假设初始的分类全部正确
49     for i = 1:size(pos)
50         if (x(pos(i),:)*w)<=0   % 查看x1分类是否错误,在x属于w1却被错误分类的情况下,wx<0
51             w = w+x(pos(i),:);% 分类错误,对权向量进行修正
52             J = 1;         % 置错误标志位为1
53         end
54     end
55     for i = 1:size(neg)
56         if (x(neg(i),:)*w)>=0    % 查看x2分类是否错误,在x属于w2却被错误分类的情况下,wx>0
57             w = w-x(neg(i),:);% 分类错误,对权向量进行修正
58             J = 1;         % 置错误标志位为1
59         end
60     end
61     if J==0                 % 代价为0,即分类均正确
62         s = 0;              % 终止迭代
63     end
64     n = n+1;            % 迭代次数加1
65     if n == N
66         s=0;
67     end
68 end
69 
70 w=[1;w(2)/w(1);w(3)/w(1)];
71 
72 %%Calculate the decision boundary line
73 plot_x = [min(x(:,2)),  max(x(:,2))];
74 plot_y = (-1./w(3)).*(w(2).*plot_x +w(1));
75 plot(plot_x, plot_y)
76 legend(Admitted, Not admitted, Decision Boundary)
77 hold off

 

perceptron and ANN